加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Shell(使用for循环读取多个参数)

(2018-08-31 16:32:22)
字符串测试操作符-n 如果不为空则为真。

[root@aa ~]# cat listarg.sh
#!/bin/bash -

# 定义变量E_BADARGS
E_BADARGS=64

# 如果特殊变量$1的值为空,则打印脚本的使用方法,并以退出状态码65退出脚本
if [ ! -n "$1" ]
then
    # 打印脚本的使用方法到标准输出
    echo "Usage: `basename $0` argument1 argument2..."

    # 退出脚本,退出状态码为65
    exit $E_BADARGS
fi

# 定义变量 index
index=1

# 打印双引号中的内容到标准输出
echo "Listing args with \$*:"

# 使用for循环遍历特殊变量$*的值
for arg in $*
do
    # 打印输出变量index和arg的值及相应内容到标准输出
    echo "Arg #$index = $arg"

    # 将变量index的值加1
    let index+=1
done

echo
# 重新将变量index的值设为1
index=1

# 打印双引号中的内容到标准输出
echo "Listing args with \"\$@\":"

# 使用for循环遍历特殊变量$@的值
for arg in $@
do
    # 打印输出变量index和arg的值及相应内容到标准输出
    echo "Arg #$index = $arg"

    # 将变量index的值加1
    let index+=1
done
[root@aa ~]# ./listarg.sh
Usage: listarg.sh argument1 argument2...
[root@aa ~]# ./listarg.sh one two three four five six seven
Listing args with $*:
Arg #1 = one
Arg #2 = two
Arg #3 = three
Arg #4 = four
Arg #5 = five
Arg #6 = six
Arg #7 = seven

Listing args with "$@":
Arg #1 = one
Arg #2 = two
Arg #3 = three
Arg #4 = four
Arg #5 = five
Arg #6 = six
Arg #7 = seven

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有