扫一扫
关注微信公众号

Shell编程概述(3)
2007-03-09   hrbpost.com

1.5 一些特殊shell变量- #和*

# ???命令行参数的数量

* ???完全的参数字符串

例子:

$ cat color4

echo There are $#?comand line argument

echo They are $*

ehco The first command line argument is $1

$ chmod +x color4

$ color4 red green yellow blue

They are 4 command line arguments

They are red green yellow blue

The first command line argument is red

$

至今为止我们看到的shell程序都不是很灵活。color3需要两个正确的参数,而my_install只需要一个。通常在你创建一个接收命令行参数的shell程序的时候,你想要用户输入一个参数的变量号码。你同时要程序执行成功,不管用户键入1个参数或是20个参数。

当处理变量参数列表的时候,特殊shell变量会提供你许多的灵活性。通过$#你可以知道有多少参数已经被输入,通过$*可以存取全部的参数列表,而不管参数的数量。请注意参数($0)不在$*这个参数列表里。

每一个命令行参数都是互相独立的,你可以通过$*集中检索这些参数,也可以通过$1,$2,$3等等来独立的检索这些参数。

一个可以接收多个命令行参数的安装程序的例子:

$ cat > my_install2

echo $0 will install $# files to your bin directory

echo The files to be installed are : $*

chmod +x $*

mv $* $HOME/bin

echo Installaton is complete

ctril + d

$ chmod +x my_install2

$ my_install2 color1 color2

my_intall2 will install 2 files to your bin directory

The files to be installed are: color1,color2

Intallaiton is complete

这个安装程序更加灵活。如果你有几个脚本要安装,你仅仅需要执行这个程序一次,只要输入多个名字即可。

非常重要的是:如果你计划传递整个参数的字符串给一个命令,这个命令必须能够接收多个参数。

在以下的脚本中,用户提供一个目录名作为一个命令行参数。程序会更改到指定的目录,显示当前的位置,并且列出内容。

$ cat list_dir

cd $*

echo You are in the $(pwd) directory

echo The contents of the directory are:

ls –F

$ list_dir dir1 dir2 dir3

sh: cd: bad argument count

由于cd命令不能同时进入到多个目录中,这个程序会发生错误。

1.6 shift 命令

向左移动所有的在*中的字符串n个位置

#的数目减少n个(n的默认值是1)

语法:shift [n]

例子:

$ cat color5

orig_args=$*

echo There are $# command line arguments

echo They are $*

echo Shifting two arguments

shift 2

echo There are $# comand line arguments

echo They are $*

echo Shifting two arguments

shift 2; final_args=$*

echo Original arguments are: $orig_args

echo Final arguments are: $final_args

shift命令会重新分配命令行参数对应位置参数,在shift n以后,所有的*中的参数会向左移动n个位置。同时#会减n。默认的n为1。Shift命令不会影响到参数0的位置。

一旦你完成一次移动,被移动出命令行的参数会丢失。如果你想在你的程序中引用这个参数,你需要在执行shift之前存贮这个参数。

Shift命令被用在:存取一组参数的位置,例如一系列的x,y的坐标从命令行删除命令选项,假定选项在参数之前。

例子:

$ color5 red green yellow orange black

There are 6 command line arguments

They are red green yellow blue orange black

Shifting two arguments

There are 4 command line arguments

They are yellow blue orange black

Shiftging two arguments

Original arguments are: red green yellow blue orange black

Final argument are : orange black

$

热词搜索:

上一篇:Shell编程概述(2)
下一篇:Shell编程概述(4)

分享到: 收藏