加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 将命令行参数与字符串进行比较

发布时间:2020-12-15 19:07:16 所属栏目:安全 来源:网络整理
导读:这是我的代码: #!/bin/bashif [ "$#" -ne 2 ] ; then echo "$0: exactly 2 arguments expected" exit 3fiif [$1 != "file" -a $1 != 'dir'] ; then echo "$0: first argument must be string "file" or "dir"" exit 1elif [-e $2 -a -r $2]; then if ["$1"
这是我的代码:
#!/bin/bash
if [ "$#" -ne 2 ] ; then
        echo "$0: exactly 2 arguments expected"
        exit 3
fi

if [$1 != "file" -a $1 != 'dir'] ; then
        echo "$0: first argument must be string "file" or "dir""
        exit 1
elif [-e $2 -a -r $2]; then
        if ["$1" = "file" -a -f $2] ; then
                echo YES
        elif ["$1" = "dir" -a -d $2] ; then
                echo YES
        else
                echo NO
        fi
        exit 0
else
        echo "$0: $2 is not a readable entry"
        exit 2
fi

如果我运行./lab4文件filename1,它将检查第一个参数是字符串“file”还是“dir”,如果第一个参数是“file”,filename1是一个文件,它将打印yes。相同的东西对于目录。

它不识别$ 1和$ 2。代码将输出:

./lab04Q2: line 7: [file: command not found
./lab04Q2: line 10: [-e: command not found

即使我在运行程序时放置了2个参数。

在bash中尝试以下3行:
if [ "a" == "a" ]; then echo hi; fi
if ["a" == "a" ]; then echo hi; fi
if ["a" == "a"]; then echo hi; fi

你会看到只有第一个工作,而另外两个没有。那就是你缺乏空间是你的表达不行的原因。

上述示例还表明您可以直接在bash提示符下测试bash语法。您可以在将它们并入您的脚本之前获得它。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读