shell编程中用户输入处理
1.命令行参数
2.脚本运行时获取输入
命令行参数 通过空格来进行分割的
位置参数 :$+position $0,$1,$2 ....
$0 :程序名
$1,$2,$3 ... $9
10及其以上的
${10}
add.sh
#/bin/bash echo "file is $0" echo "1->$1" echo "2->$2" echo "10->${10}" echo "11->${11}"
./add.sh 1 2 3 4 5 6 7 8 9 10 11
file is ./add.sh
1->1
2->2
10->10
11->11
$0表示 命令行输入的
/root/sh/f.sh
#! /bin/bash echo `basename $0` echo `dirname $0` [root@localhost110 sh]# /root/sh/f.sh f.sh /root/sh
calc.sh
#! /bin/bash name=`basename $0` if [ $name = "add" ] then result=$[$1+$2] elif [ $name="minus" ] then result=$[$1-$2] fi echo "the $name result is $result"
注意if 后的[]与变量之间必须有空格
chmod u+x calc.sh
ln -s calc.sh add
ln -s calc.sh minus
执行命令
./add 1 2
the add result is 3
./minus 5 1
the minus result is 4
命令行参数-特殊变量
1.参数计数(参数个数):$#
2.所有参数: $*
3.参数列表: $@
test.sh
#! /bin/bash echo $# echo $* echo $@ echo "#######################" for var in "$*" do echo "\$* param=$var" done echo "########################" for var in "$@" do echo "\$@ param=$var" done
执行结果
[root@localhost110 sh]# ./test.sh 1 2 js php 4 1 2 js php 1 2 js php ####################### $* param=1 2 js php ######################## $@ param=1 $@ param=2 $@ param=js $@ param=php
|
$$ |
Shell本身的PID(ProcessID) |
|
$! |
Shell最后运行的后台Process的PID |
|
$? |
最后运行的命令的结束代码(返回值) |
|
$- |
使用Set命令设定的Flag一览 |
|
$* |
所有参数列表 如"$*"用「"」括起来的情况、以"$1 $2 … $n"的形式输出所有参数。 |
|
$@ |
所有参数列表。如"$@"用「"」括起来的情况、以"$1" "$2" … "$n" 的形式输出所有参数 |
|
$# |
添加到Shell的参数个数
|
|
$0 |
Shell本身的文件名
|
$1~$n
|
Shell文件第1到第n个参数,大于9的用${n} |
$?
成功返回0 否者返回大于0 的
[root@web ~]# ll 总用量 24 -rw-------. 1 root root 1331 7月 2 2016 anaconda-ks.cfg drwxr-xr-x. 2 root root 50 3月 14 20:32 c .............................................. [root@web ~]# echo $? 0 [root@web ~]# l -bash: l: 未找到命令 [root@web ~]# echo $? 127 [root@web ~]# echo 'php'|grep a [root@web ~]# echo $? 1 [root@web ~]# echo 'php'|grep h php [root@web ~]# echo $? 0