Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Shell Passing Arguments

Shell Passing Arguments

When running a Shell script, we can pass arguments to it. The format for getting arguments inside the script is $n,n represents a number,1 is the first argument of the script,2 is the second argument of the script.

For example, you can use $1, $2, and so on to refer to the arguments passed to the script, where $1 is the first argument, $2 is the second argument, and so on.

Example

In the following example we pass three arguments to the script and output them separately, where $0 is the name of the file being executed (including the file path):

Example

#!/bin/bash

author:Runoob Tutorial

url:www.runoob.com

echo

"Shell Passing Arguments Example!"

;

echo

"Executing file name: $0"

;

echo

"The first argument is: $1"

;

echo

"The second argument is: $2"

;

echo

"The third argument is: $3"

;

Set the executable permission on the script and run it. The output is as follows:



$ chmod +x test.sh 

$ ./test.sh 1 2 3

Shell 传递参数实例!

执行的文件名:./test.sh

第一个参数为:1

第二个参数为:2

第三个参数为:3

In addition, there are several special characters for handling parameters:

Parameter handling Description
$# The number of arguments passed to the script
$* Displays all arguments passed to the script as a single string.
When "$*" is enclosed in double quotes, it outputs all arguments in the form "$1 $2 ... $n".
$$ The current process ID of the running script
$! The ID of the last process running in the background
$@ Same as $*, but when used, quotes are added and each parameter is returned within quotes.
When "$@" is enclosed in double quotes, it outputs all arguments in the form "$1" "$2" ... "$n".
$- Displays the current options used by the Shell, same asthe set commandin functionality.
$? Displays the exit status of the last command. 0 means no error; any other value indicates an error.

Example

#!/bin/bash

author:Runoob Tutorial

url:www.runoob.com

echo

"Shell Passing Arguments Example!"

;

echo

"The first argument is: $1"

;

echo

"The number of arguments is: $#"

;

echo

"Arguments displayed as a single string: $*"

;

Run the script, and the output is as follows:



$ chmod +x test.sh 

$ ./test.sh 1 2 3

Shell 传递参数实例!

第一个参数为:1

参数个数为:3

传递的参数作为一个字符串显示:1 2 3

The difference between $* and $@:

Example

#!/bin/bash

author:Runoob Tutorial

url:www.runoob.com

echo

"-- $* demo ---"

for

i

in

"$*"

;

do

   

echo

$i

done

echo

"-- $@ demo ---"

for

i

in

"$@"

;

do

   

echo

$i

done

Run the script, and the output is as follows:



$ chmod +x test.sh 

$ ./test.sh 1 2 3

-- $* 演示 ---

1 2 3

-- $@ 演示 ---

1

2

3