Skip to Content
Mastering Linux Shell Scripting - Second Edition
book

Mastering Linux Shell Scripting - Second Edition

by Mokhtar Ebrahim, Andrew Mallett
April 2018
Beginner
284 pages
7h 3m
English
Packt Publishing
Content preview from Mastering Linux Shell Scripting - Second Edition

Passing arrays

Not all your passed values will be single values; you may need to pass an array to the function. Let's see how to pass an array as a parameter:

#!/bin/bash 
myfunc() { 
   arr=$@ 
   echo "The array from inside the function: ${arr[*]}" 
} 
 
test_arr=(1 2 3) 
echo "The original array is: ${test_arr[*]}" 
myfunc ${test_arr[*]} 

From the result, you can see that the used array is returned the way it is from the function.

Note that we used $@ to get the array inside the function. If you use $1, it will return the first array element only:

#!/bin/bash myfunc() { arr=$1 echo "The array from inside the function: ${arr[*]}" } my_arr=(5 10 15) echo ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Linux Shell Scripting - Second Edition

Learning Linux Shell Scripting - Second Edition

Ganesh Sanjiv Naik
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781788990554Supplemental Content