将参数传递到简单 ShellScript 时出现问题(未找到命令)
我正在尝试编写一个简单的 shell 脚本,如果有,则打印出第一个参数,如果没有,则打印“none”。该脚本称为 test.sh
if [$1 = ""]
then
echo "none"
else
echo $1
fi
如果我运行不带参数的脚本,一切正常。但是,如果我运行此命令 source test.sh -test
,则会在脚本继续运行并正确回显测试之前收到此错误 -bash: [test: command not found
。我做错了什么?
I am trying to write a simple shell-script that prints out the first parameter if there is one and prints "none" if it doesn't. The script is called test.sh
if [$1 = ""]
then
echo "none"
else
echo $1
fi
If I run the script without a parameter everything works. However if I run this command source test.sh -test
, I get this error -bash: [test: command not found
before the script continues on and correctly echos test. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你需要在'[',']'字符之前/之后有空格,
即你需要将你的引用(实际上是所有引用)包装到$1,并使用上面编辑的引号。
修复该问题后,您可能还需要提供脚本的相对路径,即
当您收到 shell 错误消息时,使用 set -vx 来打开 shell 调试几乎总是有帮助的> 在引起麻烦的行之前,或者非常靠近脚本顶部的地方。然后您可以看到正在执行的每一行/代码块,以及 shell 正在使用的变量的值。
我希望这有帮助。
you need spaces before/after '[',']' chars, i.e.
And you need to wrap your reference (really all references) to $1 with quotes as edited above.
After you fix that, you may also need to give a relative path to your script, i.e.
When you get a shell error message has you have here, it almost always helps to turn on shell debugging with
set -vx
before the lines that are causing your trouble, OR very near the top your script. Then you can see each line/block of code that is being executed, AND the value of the variables that the shell is using.I hope this helps.