Question

This Nagios script uses ${1} and ${*} like so

if [ "${1}" ]; then
    if [ "${ERRORSTRING}" ]; then
        echo "${ERRORSTRING} ${OKSTRING}" | sed s/"^\/ "// | mail -s "$(hostname -s): ${0} reports errors\
" -E ${*}
    fi
else
    if [ "${ERRORSTRING}" -o "${OKSTRING}" ]; then
        echo "${ERRORSTRING} ${OKSTRING}" | sed s/"^\/ "//
        exit ${ERR}
    else
        echo no zpool volumes found
        exit 3
    fi
fi

Question

What does ${1} and ${*} do?

Was it helpful?

Solution

The command-line arguments $1, $2, $3,...$9 are positional parameters, with $0 pointing to the actual command, program, shell script, or function and $1, $2, $3, ...$9 as the arguments to the command.

"$*" special parameter takes the entire list as one argument with spaces between and the "$@" special parameter takes the entire list and separates it into separate arguments.

Suppose test.sh given below:

#!/bin/sh 
echo "File Name: $0" 
echo "First Parameter : $1" 
echo "First Parameter : $2" 
echo "Quoted Values: $@" 
echo "Quoted Values: $*" 
echo "Total Number of Parameters : $#"

enter image description here

OTHER TIPS

Quoting from Special Parameters in the manual:

*

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c…", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

$1 refers to a Positional Parameter.


Assume the following script:

echo "${1}"
echo "${*}"

Upon invoking by saying:

bash scriptname foo bar baz

it would produce:

foo
foo bar baz

Now observe the effect of the variable IFS. Given the script:

IFS=
echo "${1}"
echo "${*}"
echo "${@}"

Invoking it by saying:

bash scriptname "foo:hey you" bar baz

would produce:

foo:hey you
foo:hey youbarbaz
foo:hey you bar baz

$1 is used(to display or to get input for user interactively) to display First parameter.

$* is used to show all parameters entered.

 # cat schecking.sh
 #!/bin/bash
 echo "All values:" "$*"
 echo "Total number of Parameter(s) :" "$#"

 # ./schecking.sh
 All values:
 Total number of Parameter(s) : 0

 # ./schecking.sh It will help us to check
 All values: It will help us to check
 Total number of Parameter(s) : 6

 # cat schecking.sh
 #!/bin/bash
 echo "First value is:" $1
 echo "All values:" "$*"
 echo "Total number of Parameter(s) :" "$#"

 # ./schecking.sh It will help us to check
 First value is: It
 All values: It will help us to check
 Total number of Parameter(s) : 6
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top