扫一扫
关注微信公众号

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

1.3 传递数据给shell程序

$ color = lavender

$ cat color1

echo you are now running program: color1

echo the value of the variable color is : $color

$ chmod +x color1

$ color1

you ar now running program : color1

the value of the variable color is :

$ export color

$ color1

you are now running program : color1

the value of the variable color is : lavender

传递数据给shell脚本的一种方法就是通过环境。在上例中。本地变量color被赋值为lavender。然后创建了shell程序color1;然后更改为可执行权限;然后这个shell程序被执行。color1试图回送color变量的值。但是,由于color是一个本地变量,属于父shell私有的,运行color1产生的子shell不能识别这个变量,因此不能打印出它的值。当color被输出到环境中,它就可以被子shell读取。

同样,由于shell进程不能够更改父进程的环境,对一个子进程中的环境变量重新赋值不会影响到父进程环境中的值。如以下的shell脚本中的color2。

echo The original value of the variable color is $color

ech0 This program will set the value of color to amber

color=amber

echo The value of color is now $color

echo When your program concludes,display the value of the color variable

观察在你设置了color的值后有什么变化。输出这个变量,然后执行color2:

$ export color=lavender

$ echo $color

lanvender

$ color2

The original value of the variable color is lavender

The program will set the value of color to amber

The value of volor is now amber

When your progam concludes, display the value of the color variable,

$ echo $color

lanvender

1.4 shell 程序的参数

命令行:

?$ sh_program arg1 arg2 . . . argx

???$0 ???$1?? $2 ....? $X

例子:

$ cat color3

echo you are now running program: $0

echo The value of command line argument \#1 is: $1

echo The value of command line argument \#2 is : $2

$ chmod +x color3

$ color3 red green

You are now running program: color3

The value of command line argument #1 is : red

The value of command line argument #2 is: green

大多数的UNIX系统命令可以接收命令行参数,这些参数通常告诉命令它将要操作的文件或目录(cp f1 f2),另外指定的参数扩展命令的能力(ls –l),或者提供文本字符串(banner hi there)

命令行参数同样对shell程序有效。这在于传送信息给你的程序的时候十分方便。通过开发一个接收命令行参数的程序,你可以传递文件或者目录命令名给你的程序处理,就像你运行UNIX系统命令一样。你也可以定义命令行选项来让命令行使用shell程序额外的功能。

在shell程序中的命令行参数与参数在命令行的位置相关。这样的参数被称为位置参数,因为对每一个特殊变量的赋值依靠一这些参数在命令行中的位置。这些变量的变量名对应它们在命令行中的数字位置,因此这些特殊的变量名为数字0,1,2等等,一直到最后的参数被传递。变量名的存取通过同样的方法,在名字前面加上$ 符号,因此,为了存取你的shell程序中的命令行参数,你可以应用$0,$1,$2等等。在$9以后,必须使用括号:$(10),$(11),否则,shell会将$10看成是$1后面跟一个0。$0会一直保存程序或命令的名字。

以下的shell程序会安装一个程序,这个程序作为一个命令行参数被安装到你的bin目录:首先创建程序my_install,注意目录$HOME/bin应该预先存在。

$ cat > my_install

echo $0 will install $1 to your bin directory

chmod +x $1

mv $1 $HOME/bin

echo Installation of $1 is complete

ctrl + d

$ chmod +x my_intalll

$ my_install color3

my_install will install color3 to your bin directory

Installation of color3 is complete

$

这个例子中,一个程序指明第一个命令行参数为一个文件名,然后加上执行权限,然后移动到你当前目录下的bin目录下。

记住UNIX系统的惯例是存贮程序在一个叫做bin的目录下。你也许想要在你的HOME目录下创建一个bin目录,在这个目录下你可以存储你的程序文件,记住要将你的bin目录放在PATH环境变量中,这样shell才会找到你的程序。

热词搜索:

上一篇:Shell编程概述(1)
下一篇:Shell编程概述(3)

分享到: 收藏