admin 管理员组

文章数量: 1184232


2024年2月7日发(作者:neutrino)

sh传入参数

sh是Unix/Linux操作系统下的一种shell命令解释器,可以用来执行shell脚本或者命令行命令。在使用sh的时候,我们可以传入一些参数来控制脚本的执行过程。那么在sh中如何传入参数呢?

sh传入参数的方式有两种:位置参数和特殊参数。

1. 位置参数

位置参数是指在执行sh脚本时,通过命令行传入的参数,这些参数会按照位置顺序依次赋值给脚本中的变量$1、$2、$3……$n。其中$1表示第一个参数,$2表示第二个参数,以此类推。例如,我们有一个脚本,内容如下:

#!/bin/sh

echo 'The first parameter is $1'

echo 'The second parameter is $2'

如果我们在命令行执行以下命令:

$ sh apple orange

那么输出结果为:

The first parameter is apple

The second parameter is orange

2. 特殊参数

特殊参数是指在sh脚本中自带的一些特殊变量,用来获取一些特殊的信息或者控制脚本的行为。下面列出一些常用的特殊参数:

$0:表示脚本的文件名(包括路径)。

- 1 -

$#:表示传入脚本的参数个数。

$*:表示所有位置参数,以字符串形式显示,参数之间用空格分隔。

$@:表示所有位置参数,以字符串形式显示,参数之间用空格分隔,但是每个参数都是独立的字符串。

$?:表示上一条命令的退出状态,如果上一条命令执行成功,则为0,否则为非0值。

$$:表示当前进程的进程号。

例如,我们有一个脚本,内容如下:

#!/bin/sh

echo 'The script name is $0'

echo 'The number of parameters is $#'

echo 'All parameters are: $*'

echo 'The first parameter is $1'

echo 'The exit status of the last command is $?'

echo 'The process ID of the current script is $$'

如果我们在命令行执行以下命令:

$ sh apple orange banana

那么输出结果为:

The script name is

The number of parameters is 3

All parameters are: apple orange banana

- 2 -

The first parameter is apple

The exit status of the last command is 0

The process ID of the current script is 12345

总结:

通过位置参数和特殊参数,我们可以在sh脚本中传入参数并控制脚本的执行过程。对于复杂的脚本,参数的传递可以大大提高脚本的灵活性和可重用性。

- 3 -


本文标签: 参数 脚本 执行