Handle whitespaces in arguments to a bash script

前端 未结 3 2124
别那么骄傲
别那么骄傲 2020-12-11 11:46

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

The script

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


        
相关标签:
3条回答
  • 2020-12-11 12:05

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

    0 讨论(0)
  • 2020-12-11 12:15

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

    0 讨论(0)
  • 2020-12-11 12:16

    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!

    0 讨论(0)
提交回复
热议问题