1、位置参数从$0~$9,$0是程序名字,$1是第一个参数以此类推
例子:
factorial=1
for (( number = 1; number <= $1; number++ ))
do
factorial=$[ $factorial * $number ]
done
echo The factorial of $1 is $factorial.
例子2:
name=$(basename $0)
if [ $name = "addem" ]
then
total=$[ $1 + $2 ]
elif [ $name = "multem" ]
then
total=$[ $1 * $2 ]
fi
echo
echo The calculater value is $total
2、特殊变量$#含有脚本运行的命令行参数的个数,不是每个参数的值
例子:
if [ $# -ne 2 ]
then
echo
echo Usage: test9.sh a b
echo
else
total=$[ $1 + $2 ]
echo
echo The total is $total
echo
fi
3、命令行参数的最后一个是什么可以通过${!#}来显示
例子:
params=$#
echo
echo The last parameter is $params
echo The last parameter is ${!#}
echo
4、访问每个参数的值可以用$*和$@变量,$*是将命令行参数作为一个整体,而$@会单独处理每一个命令行参数
例子:
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
代码结果为:
$* Parameter #1 = 1 2 3
$@ Parameter #1 = 1
$@ Parameter #2 = 2
$@ Parameter #3 = 3 (区别就在这里)
5、移动变量:移动变量使用的是shift命令,可以将$2命令行参数移至$1,而之前$1里面的值将会被删除
例子:
echo
count=1
while [ -n "$1" ]
do
echo "Parameter #$count = $1"
count=$[ count + 1 ]
shift
done
一次性移动几个位置:在shift后面写上数字
例子:
echo
echo "The original parameters: $*"
shift 2
echo "Here's the new first parameter: $1"
6、获得用户的输入:使用read命令来获取用户的输入,-p选项顺便带了打印功能,减少了echo的数量
echo -n "Enter your name: "
read name
echo "Hello $name, welcome to muy program."
----------------------------------------------------------------
read -p "Please enter you age: " age
days=$[ $age * 365 ]
echo "That makes you over $days days old!"
如果read命令中不指定变量,那么默认存在环境变量REPLY中
例子:
read -p "Enter you name: "
echo
echo Hello $REPLY, welcome to my program.
-t选项则指定了超时时间,超过了定义时间不输入就会自动结束read输入
-s选项可以在隐藏你在read上的输入,就像登陆系统看不见密码一样
-n选项指定了输入的字符数
7、通过read line来读取文件中的数据:read line则可以读取文件中的每一行
例子:
count=1
cat test | while read line
do
echo "Line $count: $line"
count=$[ count + 1 ]
done
echo "Finished processing the file"