3、在Shell程序中使用的参数

来源:互联网 发布:广州seo搜索引擎优化 编辑:程序博客网 时间:2024/06/11 06:42

3、在Shell程序中使用的参数

学习目标
位置参数
内部参数

如同ls命令可以接受目录等作为它的参数一样,在Shell编程时同样可以使用参数。Shell程序中的参数分为位置参数和内部参数等。

12-3-1 位置参数
由系统提供的参数称为位置参数。位置参数的值可以用$N得到,N是一个数字,如果为1,即$1。类似C语言中的数组,Linux会把输入的命令字符串分段并给每段进行标号,标号从0开始。第0号为程序名字,从1开始就表示传递给程序的参数。如$0表示程序的名字,$1表示传递给程序的第一个参数,以此类推。

12-3-2  内部参数
上述过程中的$0是一个内部变量,它是必须的,而$1则可有可无,最常用的内部变量有$0、$#、$?、$*,它们的含义如下。
$0: 含命令所在的路径。
$#: 传递给程序的总的参数数目。
$?: Shell程序在Shell中退出的情况,正常退出返回0,反之为非0值。
$*: 传递给程序的所有参数组成的字符串。

实例:编写一个Shell程序,用于描述Shell程序中的位置参数为:$0、$#、$?、$*,程序名为test1,代码如下:

复制代码
root@ubuntu:~$ vi test1#! /bin/sh echo "Program name is $0";echo "There are totally $# parameters passed to this program";echo "The last is $?";echo "The parameter are $*"; root@ubuntu:~$ ./test1 this is a test program //传递5个参数执行后的结果如下:Program name is ./test1 //给出程序的完整路径和名字There are totally 5 parameters passed to this program //参数的总数The last is 0 //程序执行效果The parameter are this is a test program  //返回由参数组成的字符串
复制代码
 

注意:命令不计算在参数内。
        
实例:利用内部变量和位置参数编写一个名为test2的简单删除程序,如删除的文件名为a,则在终端中输入的命令为:test a。
分析:除命令外至少还有一个位置参数,即$#不能为0,删除不能为$1,程序设计过程如下。

复制代码
1)、用vi编辑程序root@ubuntu:~$ #vi test2#! /bin/sh if test $# -eq 0    then echo "Please specify a file!"else    gzip $1 //现对文件进行压缩    mv $1.gz $HOME/dustbin //移动到回收站    echo "File $1 is deleted !"          fi 2)、设置权限root@ubuntu:~$ chmod +x test2 3)、运行root@ubuntu:~$ ./test2Please specify(指定) a file!root@ubuntu:~$ ./test2 agzip: a: No such file or directorymv: cannot stat `a.gz': No such file or directoryFile a is deleted !root@ubuntu:~$ touch aroot@ubuntu:~$ ./test2 a  (如果a文件在当前目录下存在) File a is deleted !
复制代码
0 0
原创粉丝点击