linux shell 特殊参数总结

来源:互联网 发布:伟大复兴 知乎 编辑:程序博客网 时间:2024/05/19 00:42
特殊参数:
(1)$*: 代表所有参数,其间隔为IFS内定参数的第一个字元
(2)$@: 与*星号类同。不同之处在於不参照IFS
(3) $#: 代表参数数量
(4)$?: 执行上一个指令的返回值
(5) $-: 最近执行的foreground pipeline的选项参数
(6)$$: 本身的Process ID
(7) $!: 执行上一个背景指令的PID
(8)$_: 显示出最後一个执行的命令


实例1:[root@CentOS5 ~]# vim param
#!/bin/sh

echo "script name                       :$0"       #$0表示脚本名
echo "first parameter                   :$1"            #第一个参数
echo "second parameter                  :$2"
echo "third parameter                   :$3"
echo "fourth parameter                  :$4"
echo "fifth parameter                   :$5"
echo "sixth parameter                   :$6"
echo "seventh parameter                 :$7"
echo "eighth parameter                  :$8"
echo "ninth parameter                   :$9"
echo "The number of arguments passed    :$#"            #返回参数个数
echo "Show all arguments                :$*"            #返回所有参数
echo "Show me my process ID             :$$"            #返回脚本运行的当前进程ID号
echo "Show me the arguments in quotes   :$@"            #与$*一样
echo "Did my script go with any errors  :$?"            #返回最后命令的退出状态,即是否执行成功,0表示成功;1表示失败;

[root@CentOS5 ~]# ./param Did you see the full moon
script name                     :./param
first parameter                 :Did
second parameter                :you
third parameter                 :see
fourth parameter                :the
fifth parameter                 :full
sixth parameter                 :moon
seventh parameter               :
eighth parameter                :
ninth parameter                 :
The number of arguments passed  :6
Show all arguments              :Did you see the full moon
Show me my process ID           :11450
Show me the arguments in quotes :Did you see the full moon
Did my script go with any errors:0


假如 ,要将两个参数合为一个参数,可以用双引号来实现,如:
[root@CentOS5 ~]# ./param Did you see the "full moon"

例如,当一条命令执行有误时,返回值为1,我们可以用以下命令来实现。
[root@CentOS5 ~]# mkdir /tm/aa
mkdir: 无法创建目录 “/tm/aa”: 没有那个文件或目录
[root@CentOS5 ~]# echo $?
1

写成脚本,我们可以用以下方法:
[root@CentOS5 ~]# vim test.sh
#!/bin/sh

mkdir /tm/aa >/dev/null 2>&1
mkdir_status=$?
echo $mkdir_status

[root@CentOS5 ~]# chmod +x test.sh
[root@CentOS5 ~]# ./test.sh

1