Shell脚本编程(三):shell参数传递

我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$nn 代表一个数字,1 为执行脚本的第一个参数,2 为执行脚本的第二个参数,以此类推……

实例

以下实例我们向脚本传递三个参数,并分别输出,其中 $0 为执行的文件名:

#!/bin/bash
# author:hong
echo "current file name is $0"
echo "first param name is $1"
echo "first param name is $2"
echo "first param name is $3"

为脚本设置可执行权限,并执行脚本,输出结果如下所示:

[root@localhost shelltest]# chmod +x test.sh
[root@localhost shelltest]# ./test.sh p1 p2 p3
./test.sh: line 1: uthor:hong: command not found
current file name is ./test.sh
first param name is p1
first param name is p2
first param name is p3

处理参数的特殊字符

参数处理说明
$# 传递到脚本的参数个数
$* 以一个单字符串显示所有向脚本传递的参数。
如"$*"用「"」括起来的情况、以"$1 $2 … $n"的形式输出所有参数。
$$ 脚本运行的当前进程ID号
$! 后台运行的最后一个进程的ID号
$@ 与$*相同,但是使用时加引号,并在引号中返回每个参数。
如"$@"用「"」括起来的情况、以"$1" "$2" … "$n" 的形式输出所有参数。
$- 显示Shell使用的当前选项,与set命令功能相同。
$? 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。

#!/bin/bash
# author:hong
# echo "current file name is $0"
# echo "first param name is $1"
# echo "first param name is $2"
# echo "first param name is $3"
echo "all the param num is $#"
echo "all the param print by a string is $*"
echo "running process id num is $$"
echo "last id num is $!"
echo "all the param print by quotation marks is $@"
echo "show the shell opition: $-"
echo "show the last commond exit state: $?"

执行脚本结果

[root@localhost shelltest]# ./test.sh p1 p2 p3
all the param num is 3
all the param print by a string is p1 p2 p3
running process id num is 11842
last id num is
all the param print by quotation marks is p1 p2 p3
show the shell opition: hB
show the last commond exit state: 0

$* 与 $@ 区别

  • 相同点:都是引用所有参数。
  • 不同点:只有在双引号中体现出来。假设在脚本运行时写了三个参数 1、2、3,,则 " * " 等价于 "1 2 3"(传递了一个参数),而 "@" 等价于 "1" "2" "3"(传递了三个参数)。

示例

#!/bin/bash
# author:hong

echo "-- $* 演示 ---"
for i in "$*"; do
    echo $i
done

echo "-- $@ 演示 ---"
for i in "$@"; do
    echo $i
done

结果

[root@localhost shelltest]# chmod +x test1.sh
[root@localhost shelltest]# ./test1.sh p11 p22 p33
-- $* 演示 ---
p11 p22 p33
-- $@ 演示 ---
p11
p22
p33
原文地址:https://www.cnblogs.com/shamo89/p/10270604.html