Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grouping in shell script

Tags:

bash

shell

sh

While passing arguments to a function, how to group parameters into a single argument? example

if my script file "my_script.sh" has a function like

    echo_arguments() {
    echo $1
    } 
    echo_arguments $1

Now in unix command line, How to specify parameters as a single arguments?

    ./my_spcript.sh a b c d        #these "a b c d" must fit in $1
like image 946
Nathan Pk Avatar asked Apr 21 '26 21:04

Nathan Pk


1 Answers

You can group several words into a single parameter in several ways:

./my_spcript.sh 'a b c d'
./my_spcript.sh "a b c d"
./my_spcript.sh a\ b\ c\ d

Basically, they all come down to telling the shell to treat the spaces as part of a parameter, rather than separators between parameters. All of the above run the script with $1 set to a b c d, and $2, $3, etc unset.

However, when you expand $1 without quotes, like this:

echo_arguments $1

The shell expands $1 and then resplits it treating the spaces as separators between parameters. So while my_spcript.sh gets a b c d as a single parameter, echo_arguments gets each letter as a separate parameter. Usually, the best way to fix this is to put $1 in double-quotes to keep it from being re-split (and prevent some other probably undesirable stray parsing as well):

echo_arguments "$1"

As a general rule, whenever you substitute a variable, you should wrap it in double-quotes to prevent the sort of problem you're seeing. There are cases when you want the additional parsing, so you don't want the double-quotes; but unless you have a specific reason for wanting the shell to do the extra parsing, use double-quotes to save headaches.

For your specific example, another way to "fix" this would be to make echo_arguments echo all of its arguments, not just the first:

echo_arguments() {
    echo "$@"
} 

Note that "$@" expands to all of the current script/function's arguments, each one treated as a separate argument to the command/function they're being passed to (essentially, they're passed through intact).

like image 199
Gordon Davisson Avatar answered Apr 23 '26 13:04

Gordon Davisson