Bash:在简单的变量赋值中“找不到命令”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6969054/
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
Bash: "command not found" on simple variable assignment
提问by beatgammit
Here's a simple version of my script which displays the failure:
这是我的脚本的一个简单版本,它显示了失败:
#!/bin/bash
${something:="false"}
${something_else:="blahblah"}
${name:="file.ext"}
echo ${something}
echo ${something_else}
echo ${name}
When I echo the variables, I get the values I put in, but it also emits an error. What am I doing wrong?
当我回显变量时,我得到了我输入的值,但它也会发出错误。我究竟做错了什么?
Output:
输出:
./test.sh: line 3: blahblah: command not found
./test.sh: line 4: file.ext: command not found
false
blahblah
file.ext
The first two lines are being emitted to stderr, while the next three are being output to stdout.
前两行被发送到 stderr,而接下来的三行被输出到 stdout。
My platform is fedora 15, bash version 4.2.10.
我的平台是 fedora 15,bash 版本 4.2.10。
采纳答案by Ignacio Vazquez-Abrams
Putting a variable on a line by itself will execute the command stored in the variable. That an assignment is being performed at the same time is incidental.
将变量单独放在一行中将执行存储在变量中的命令。同时执行任务是偶然的。
In short, don't do that.
简而言之,不要那样做。
echo ${something:="false"}
echo ${something_else:="blahblah"}
echo ${name:="file.ext"}
回答by Micha? ?rajer
You can add colon:
您可以添加冒号:
: ${something:="false"}
: ${something_else:="blahblah"}
: ${name:="file.ext"}
The trick with a ":" (no-operation command) is that, nothing gets executated, but parameters gets expanded. Personally I don't like this syntax, because for people not knowing this trick the code is difficult to understand.
使用“:”(无操作命令)的技巧是,没有执行任何操作,但参数会被扩展。我个人不喜欢这种语法,因为对于不知道这个技巧的人来说,代码很难理解。
You can use this as an alternative:
您可以使用它作为替代:
something=${something:-"default value"}
or longer, more portable (but IMHO more readable):
或更长时间,更便携(但恕我直言,更具可读性):
[ "$something" ] || something="default value"
回答by Karoly Horvath
It's simply
简直就是
variable_name=value
If you use $(variable_name:=value}bash substitutes the variable_name if it is set otherwise it uses the default you specified.
如果您使用$(variable_name:=value}bash 替换 variable_name 是否设置,否则它将使用您指定的默认值。

