bash 将命令行参数与字符串进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9254938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing command-line parameter to a string
提问by JA3N
Here is my code:
这是我的代码:
#!/bin/bash
if [ "$#" -ne 2 ] ; then
echo "./lab04Q2: line 7: [file: command not found
./lab04Q2: line 10: [-e: command not found
: exactly 2 arguments expected"
exit 3
fi
if [ != "file" -a != 'dir'] ; then
echo "if [ "a" == "a" ]; then echo hi; fi
if ["a" == "a" ]; then echo hi; fi
if ["a" == "a"]; then echo hi; fi
: first argument must be string "file" or "dir""
exit 1
elif [-e -a -r ]; then
if ["" = "file" -a -f ] ; then
echo YES
elif ["" = "dir" -a -d ] ; then
echo YES
else
echo NO
fi
exit 0
else
echo "if [ != "file" -a != 'dir' ] ;
: is not a readable entry"
exit 2
fi
If I run ./lab4 file filename1
it will check if the first parameter is the string "file" or "dir" then if the first parameter is "file" and filename1 is a file, it will print yes. Same thing for dir.
如果我运行./lab4 file filename1
它会检查第一个参数是字符串“file”还是“dir”然后如果第一个参数是“file”并且filename1是一个文件,它会打印yes。dir 也是一样。
It doesn't recognize $1
and $2
. The code will output:
它不识别$1
和$2
。代码将输出:
even though I did put 2 parameters when running the program.
即使我在运行程序时确实输入了 2 个参数。
回答by Stephen Quan
Try the following 3 lines in bash:
在 bash 中尝试以下 3 行:
##代码##You'll see that only the first one works, whereas the other two do not. i.e. it's your lack of spaces is the reason why your expression doesn't work.
您会看到只有第一个有效,而其他两个无效。即你的空间不足是你的表达不起作用的原因。
The above example also suggests that you can test out bash syntax directly on the bash prompt. You can get it right before incorporating them into your script.
上面的示例还建议您可以直接在 bash 提示符下测试 bash 语法。在将它们合并到您的脚本之前,您可以正确地完成它。
回答by SiegeX
The problem(s) come from the fact that [
is actually a command. In fact it's an alias for the test
command. In order for this to run properly, you'll need to add a space after your [
as in:
问题来自[
实际上是命令的事实。事实上,它是test
命令的别名。为了使其正常运行,您需要在以下内容后添加一个空格[
:
Do this for all your instances of [
that don't have a space after it.
对[
后面没有空格的所有实例执行此操作。
P.S.
聚苯乙烯
Since you're using bash
as your interpreter, I highly suggest you use [[ ]]
instead of [ ]
for your tests as the former is a lot more capable than the latter with no downsides; no need for a space is one of them
由于您bash
用作解释器,因此我强烈建议您使用[[ ]]
而不是[ ]
用于测试,因为前者比后者功能强大得多,而且没有任何缺点;不需要空间就是其中之一