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:~$ ./test2
Please specify(指定) a file!
root@ubuntu:~$ ./test2 a
gzip: a: No such file or directory
mv: cannot stat `a.gz': No such file or directory
File a is deleted !
root@ubuntu:~$ touch a
root@ubuntu:~$ ./test2 a  (如果a文件在当前目录下存在) 
File a is deleted !
 
原文地址:https://www.cnblogs.com/linjiqin/p/3148646.html