Ulrik
Ulrik

Reputation: 1141

Argument grouping in bash scripts

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?

Upvotes: 0

Views: 127

Answers (1)

Junior Dussouillez
Junior Dussouillez

Reputation: 2397

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

Upvotes: 2

Related Questions