[SOLVED] Passing and Catching arrays with spaces in elements to functions. How?
by ddenial from LinuxQuestions.org on (#56NK2)
Hello All
I'm trying to pass multiple filenames with a single option from getopts to function. In function, I want to deal with all files one-by-one.
This is the code:
Code:$ ll file*
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 file1.txt
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 'file 2.txt'
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 file3.txt
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 file4.txt
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 file5.txt
$ cat array.sh
#!/bin/bash
show_array() {
catch_arr=("$@")
for i in "${catch_arr[@]}"; do
echo "${i}"
done
}
while getopts ":f:" opt ; do
case $opt in
f) files+=("$OPTARG")
show_array "${files[@]}"
;;
:) echo "Error: -$OPTARG requires an argument" ; exit 1 ;;
?) echo "Error: unknown option -$OPTARG" ; exit 1 ;;
esac
done
$ ./array.sh -f file1.txt -f 'file 2.txt' -f file3.txt
file1.txt
file1.txt
file 2.txt
file1.txt
file 2.txt
file3.txtI'm getting this strange output. How do I pass array with elements and catch them properly in function?
Thanks


I'm trying to pass multiple filenames with a single option from getopts to function. In function, I want to deal with all files one-by-one.
This is the code:
Code:$ ll file*
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 file1.txt
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 'file 2.txt'
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 file3.txt
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 file4.txt
-rw-rw-r--. 1 neon neon 0 Aug 7 18:53 file5.txt
$ cat array.sh
#!/bin/bash
show_array() {
catch_arr=("$@")
for i in "${catch_arr[@]}"; do
echo "${i}"
done
}
while getopts ":f:" opt ; do
case $opt in
f) files+=("$OPTARG")
show_array "${files[@]}"
;;
:) echo "Error: -$OPTARG requires an argument" ; exit 1 ;;
?) echo "Error: unknown option -$OPTARG" ; exit 1 ;;
esac
done
$ ./array.sh -f file1.txt -f 'file 2.txt' -f file3.txt
file1.txt
file1.txt
file 2.txt
file1.txt
file 2.txt
file3.txtI'm getting this strange output. How do I pass array with elements and catch them properly in function?
Thanks