Handle whitespaces in arguments to a bash script

2020-02-06 11:01发布

问题:

I am having issues handling arguments that contain white spaces in a my bash script.

The script

#!/bin/bash
for i in $*
do
    echo "$i"
done

The call (with 2 arguments)

$ ./script.sh "a b" "c"

The actual output (as if there were 3 arguments)

a
b
c

The expected output (as if there were 2 arguments)

a b
c

Can someone explain how to get the expected output?

回答1:

Change $* to "$@" on the first line.



回答2:

What you want is $@ for the parameters (and you have to enclose it in "") instead of $*.



回答3:

Replying to the comment left in 2011 on how to assign each argument to a variable...

This bash function assigns each argument to an item in an array. These can then be used elsewhere.

The function in question finds files of a certain type and then greps them:

search "multi word search terms" txt

The relevant lines are the the first 5. We initialise an array, loop over the arguments passed, and assign them as items in the array. These are then referenced by the function as required.

This way you can specify an optional 3rd parameter to open the files in an editor of your choice:

search "multi word search terms" txt mate

The variable $searchterm has had spaces escaped so that grep will accept it as one string.

function search() {
        terms=();
        for i in "$@"
        do
                terms+=("$i")
        done

        file='*.'${terms[1]};
        searchterm=${terms[0]// /\\ };

        if [ -n "$3" ]; then
                find . -type f -name $file -exec grep -irl "$searchterm" {} \; | xargs ${terms[2]};
        else
                find . -type f -name $file -exec grep -irl "$searchterm" {} \;;
        fi
}

Hope this helps someone!