Linux Command Line and Shell Scripting Bible__第11章
时间:2010-09-16 来源:way_testlife
Linux Command Line and Shell Scripting Bible__第11章
第11章 处理用户输入
向shell脚本传递数据的最基本方式是使用:命令行参数。
位置参数:$0为程序名称,$1为第一个参数,$2为第二个参数,……直到$9为第9个参数。第9个变量之后,必须使用大括号将变量括起来,如${10}。
读取程序名称:传递给变量$0的字符实际上是程序的完整路径,可通过basename命令只返回程序名称。
#!/bin/bash
# using basename with the $0 parameter
name=`basename $0`
echo The command entered is: $name
返回程序的名称。
特殊变量 $# 中存储执行脚本时包含的命令行参数的个数。
虽然 $# 能返回参数个数,但 ${$#} 却不能得到最后一个命令行参数值。因为在大括号中不能使用美元符号,必须将美元符号替换为感叹号,即 ${!#}
$* $@ 这两个变量都是在一个变量中包含所有命令行参数。
$* 将所有参数视为一个单词
$@ 分别对待每个参数

#!/bin/bash
# testing $* and $@
count=1
for param in "$*"
do
echo "\$* Parameter $count = $param
done
count=1
for param in "$@"
do
echo "\$@ Parameter $count = $param"
done
py-way@my-stage:~/work/Shell_prog$ ./test12 1 a 3 d
$* Parameter 1 = 1 a 3 d
$@ Parameter 1 = 1
$@ Parameter 2 = a
$@ Parameter 3 = 3
$@ Parameter 4 = d
shift命令帮助操作命令行参数,能够改变命令行参数的相对位置。
默认将每个参数变量左移一个位置。变量$3的值移给变量$2,变量$2的值移给$1,而变量$1的值则被丢弃(变量$0的值和程序名称保持不变)。
处理选项:选项是由破折号引导的单个字母,它更心命令的行为。

#!/bin/bash
# extracting options and parameters
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found -a options.";;
-b) echo "Found -b options.";;
-c) echo "Found -c options.";;
*) echo "$1 is not an option."
esac
shift
done
# ./test -a -b -c -d
Found -a option.
Found -b option.
Found -c option.
-d is not an option.
#
执行shell脚本时经常会遇到需要使用选项又需要使用参数的情况,在linux中的标准方式是通过特殊字符码将二者分开,这个特殊字符码是双破折号(--)。shell使用双破折号指示列表的结束。

#!/bin/bash
# extracting command line options and values
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found -a option."
-b) param=$1
echo "Found -b option, with parameter valus $param."
-c) echo "Found -c option."
--) shift
break
*) echo "$1 is not an option."
esac
shift
done
count=1
for param in "$1"
do
echo "Parameter #$count: $param."
count=$[ $count+1 ]
done

#!/bin/bash
# extracting command line options and values with getopt
set -- `getopt -q ab:c "$@"`
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option.";;
-b) param=$2
echo "Found the -b option, with parameter value $param."
shift 2;;
-c) echo "Found the -c option.";;
--) shift
break;;
*) echo "$1 is not an option."
esac
shift
done
count=1
for param in "$@"
do
echo "Parameter #$1: $param"
count=$[ $count+1 ]
done
----------------
获取用户输入
read命令接受标准输入(键盘)的输入,或其他文件描述符的输入。得到输入后,read命令将数据放入一个标准变量中。
-n 该选项抑制字符串结尾的新行符,允许用户在字符串后面立即输入数据,而不是在下一行中输入
-p 允许在read命令行中直接指定一个提示
在read命令行中也可不指定变量,如果不指定变量,那么read命令会将接收到的数据放置在环境变量REPLY中。
-t 指定一个计时器,指定read命令等待输入的秒数。
-n1 提示read命令中要接收到一个字符就退出。
默读
-s 能够使read命令中输入的数据不显示在监视器上(实际上,数据是显示的,只是read命令将文本颜色设置成了与背景相同的颜色)
读取文件
每调用一次read命令,都会读取文件中的一行文本。