Shell Passing Arguments

Arguments can be passed to the script when it is executed,we can get the arguments by the formats like $n.Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.

For example

In the following example, the script name is followed by 3 arguments and will output these arguments separately and the variable $0 references to the current script file name.

#!/bin/bash
# author:ylspirit
# url:www.linuxcommands.site

echo "shell passing arguments example!";
echo "the current script file name:$0";
echo "the first argument:$1";
echo "the second argument:$2";
echo "the third argument:$3";

Set executable permissions for the script, and execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
shell passing arguments example!
the current script file name:./test.sh
the first argument:1
the second argument:2
the third argument:3

The following table shows a number of special variables that you can use in your shell scripts

VariableDescription
$#The number of arguments supplied to a script.
$*Represent all parameters passed to the script in a single string.All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.
$$The process number of the current shell. For shell scripts, this is the process ID under which they are executing.
$!The process number of the last background command.
$@This is similar to the $*, but the difference is that $@ should add double quoted in which to get the arguments.All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to “$1” “$2”.
$-Show the current opitions like shell command set
$?The exit status of the last command executed.
#!/bin/bash
# author:ylspirit
# url:www.linuxcommands.site

echo "shell passing arguments example!";
echo "the first argument:$1";

echo "the number of arguments:$#";
echo "show all parameters passed:$*";

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
shell passing arguments example!
the first argument:1
the number of arguments:3
show all parameters passed:1 2 3

The differences between the $* and $@:

  • similarities:represent all parameters
  • differences:All the arguments are individually double quoted or not.If we pass three arguments like 1、2、3,” * ” is equal to “1 2 3″(pass one param),but “@” is equal to “1” “2” “3”(pass three params)
#!/bin/bash
# author:ylspirit
# url:www.linuxcommands.site

echo "-- \$* demo ---"
for i in "$*"; do
    echo $i
done

echo "-- \$@ demo ---"
for i in "$@"; do
    echo $i
done

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
-- $* demo ---
1 2 3
-- $@ demo ---
1
2
3

Add a Comment

Your email address will not be published. Required fields are marked *