0

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

You shouldn't use the function keyword to define functions. Your function should be defined as test() { ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.