Linux shell编程学习笔记(四) 位置变量

本文介绍了Shell脚本中的位置变量概念及其应用,包括如何通过位置变量传递参数给脚本,以及如何在脚本中使用这些变量进行条件判断和命令执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、位置变量

也称系统变量或位置参数,是shell脚本运行时,传递给脚本的参数

名称以数字命名,如:$1, $2, ${10}

测试程序如下:

#!/bin/bash
#test.sh
#test var
#by wzs 2017/10/23
echo "the number of parameters is $#"
echo "the return code of last command is $?"
echo "the script name is $0"
echo "the parameters is $*"
echo "\$1 = $1; \$2 = $2"

运行结果如下:

book@wzs:~/work/tq210/shell$ ./test.sh aa bb
the number of parameters is 2
the return code of last command is 0
the script name is ./test.sh
the parameters is aa bb
$1 = aa; $2 = bb

脚本中判断前一个命令的返回值,一般成功返回0,失败返回非0,如下:

#!/bin/bash
#test.sh
#test var
#by wzs 2017/10/23
if [ $# -ne 2 ];
then
        echo "Usage:$0 string files";
        exit 1;
fi

grep $1 $2 -nR;

if [ $? -ne 0 ];
then
        echo "Not found \"$1\" in $2";
        exit 1;
fi

echo "Found \"$1\" in $2";

执行方式一:

book@wzs:~/work/tq210/shell$ ./test.sh xxx bb.txt 
Not found "xxx" in bb.txt

由于在bb.txt文件里没有匹配到"xxx"所以,grep命令返回非0


执行方式二:

book@wzs:~/work/tq210/shell$ ./test.sh a bb.txt 
1:fda
2:afda
Found "a" in bb.txt

匹配到字符"a",所以grep命令返回值是0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值