shell 读取参数

bash sell 会将一些成为位置参数的特殊变量分配给输入到命令行参赛中的所有参数
位置参数三标准的数字:$0是程序名,$1是第一个参数 $2是第二个参数
,依次类推,直到第九个参数$9

使用$1

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

The factorial of 9 362880

使用$0

#!/bin/bash
echo The zero parameter is set to: $0

The zero parameter is set to: ./test3.sh

当脚本认为参数变量中会有数据而实际上并没有是,脚本很有可能会产生错误消息.这种鞋脚本的方法并不可取.使用参数前一定要检查其中是否存在数据

if [ -n "$1" ]
then
	echo hello $1 , glad t meet you.
	else
	echo "Sorry, you did no identify yourself. "
	fi

使用$# 统计参数个数

#!/bin/bash
echo The were $# parameters supplied.

./param.sh 
The were 0 parameters supplied.

 ./param.sh 99
The were 1 parameters supplied.

./param.sh 1 2 3 546 48
The were 5 parameters supplied.

抓取所有的数据
使用$* 和 $@ 变量可用来访问所有的参数
$* 变量会将命令行上提供的所有参数当做一个单词保存.
$@ 会将命令行上提供的所有参数当作同一个字符串中多个独立的单词.这里就能够遍历所有的参数值
得到每一个参数,通常用for命令完成

#!/bin/bash
echo "Using the \$* method: $*"
echo
echo "Using the \$@ method: $@"
#!/bin/bash
echo 
count=1
for param in "$*"
do
    echo "\$* Parameter #$count = $param"
    count=$[ $count + 1 ]
done
#
echo 
count=1
for param in "$@"
do 
    echo "\$@ Parameter #$count= $param"
    count=$[ $count +  1 ]
done



./test5.sh rich dog cat 

$* Parameter #1 = rich dog cat

$@ Parameter #1= rich
$@ Parameter #2= dog
$@ Parameter #3= cat

移动变量shift
使用shift命令是,默认情况下会将每个参数向左移动一个位置。所以
$3的值会移动到$2中,而$1的值会被删除

#!/bin/bash
echo 
count=1
while [ -n "$1" ]
do 
    echo " parameter #$count =$1 "
    count=$[ $count + 1 ]
    shift 
done

猜你喜欢

转载自blog.csdn.net/gameloftnet/article/details/84311133