bash 将参数传递到 Simple ShellScript 时出现问题(找不到命令)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7919922/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:00:20  来源:igfitidea点击:

Trouble Passing Parameter into Simple ShellScript (command not found)

macosbashshellunixscripting

提问by Spencer

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

我正在尝试编写一个简单的 shell 脚本,如果有,则打印出第一个参数,如果没有,则打印“none”。该脚本名为 test.sh

    if [ = ""]
    then
        echo "none"
    else
        echo 
    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 foundbefore the script continues on and correctly echos test. What am I doing wrong?

如果我在没有参数的情况下运行脚本,一切正常。但是,如果我运行此命令source test.sh -test,则会-bash: [test: command not found在脚本继续运行并正确响应测试之前收到此错误。我究竟做错了什么?

回答by shellter

you need spaces before/after '[',']' chars, i.e.

在 '[',']' 字符之前/之后需要空格,即

if [ "" = "" ] ; then
#---^---------^ here
   echo "none"
else
    echo ""
fi

And you need to wrap your reference (really all references) to $1 with quotes as edited above.

并且您需要使用上面编辑的引号将您的参考文献(实际上是所有参考文献)包装到 $1 中。

After you fix that, you may also need to give a relative path to your script, i.e.

修复该问题后,您可能还需要提供脚本的相对路径,即

source ./test.sh -test
#------^^--- there

When you get a shell error message has you have here, it almost always helps to turn on shell debugging with set -vxbefore 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.

当您在此处收到 shell 错误消息时set -vx,在导致您遇到问题的行之前或在脚本顶部附近打开 shell 调试几乎总是有帮助的。然后您可以看到正在执行的每一行/代码块,以及 shell 正在使用的变量的值。

I hope this helps.

我希望这有帮助。