I have a bash script with a lot of functions that process all arguments received by the script. The problem is, if I use myfunction $@ or myfunction $*, the arguments that contain space characters will be interpreted the wrong way, so I have to use myfunction "$1" "$2" "$3" ..., which is immature and limits the number of arguments to 9. Is there a way to solve this problem, perhaps by somehow making received arguments global? Or is there some other trick that makes this possible?
Add a comment
|
1 Answer
You can use quotes to prevent this.
Examples :
test() {
for i in "$@"
do
echo "$i"
done
}
test "$@"
Output :
$ ./test.sh foo "bar baz"
foo
bar baz
Without quotes :
test() {
for i in $@ # no quotes
do
echo "$i"
done
}
test "$@"
Output :
$ ./test.sh foo "bar baz"
foo
bar
baz
Or
test() {
for i in "$@"
do
echo "$i"
done
}
test $@ # no quotes
Output :
$ ./test.sh foo "bar baz"
foo
bar
baz
1 Comment
gniourf_gniourf
You shouldn't use the
function keyword to define functions. Your function should be defined as test() { ....