shell-处理用户输入

命令行参数

 #./admin 10 30

读取参数

[root@localhost scrips]# vi test28.sh

#!/bin/bash
factorial=1
for ((number=1; number<=$1; number++))
do
factorial=$[ $factorial * $number ]        #factorial=$(($factorial * $number))
done
echo "Then factorial of $1 is $factorial"

[root@localhost scrips]# bash test28.sh 5
Then factorial of 5 is 120

[root@localhost scrips]# vi test29.sh

#!/bin/bash
total=$(($1*$2))
echo "The first parameter is $1."
echo "The second parameter is $2."
echo "The total value is $total"

[root@localhost scrips]# bash test29.sh 2 5
The first parameter is 2.
The second parameter is 5.
The total value is 10

如果脚本需要的命令行参数不止个,你仍然可以处理,但是需要稍微修改一下变量名,在第9个变量之后,你必须在变量数字周围上花括号,经如${10}。

读取脚本名

#echo "The zero parameter is set to: $0"    #$0是读取脚本名用的变量。

[root@localhost scrips]# vi test1a.sh

#!/bin/bash
name=$(basename $0)       
echo                 
echo "The script name is: $name"

[root@localhost scrips]# bash test1a.sh

The script name is: test1a.sh

测试参数

[root@localhost scrips]# vi test2a.sh

#!/bin/bash
if [ -n "$1" ]
then
echo "Hello $1, glad to meet you."
else
echo "Sorry, you did not identify yourself"
fi

[root@localhost scrips]# bash test2a.sh
Sorry, you did not identify yourself
[root@localhost scrips]# bash test2a.sh 4
Hello 4, glad to meet you.

特殊参数变量

参数统计

  $#示例

[root@localhost scrips]# vi file1.sh

#!/bin/bash
echo "There were $# parameters supplied."

[root@localhost scrips]# bash file1.sh 1 2 3 4 5
There were 5 parameters supplied.

猜你喜欢

转载自www.cnblogs.com/liujunjun/p/11927733.html
今日推荐