bash 设置变量时找不到bash命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26178654/
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 when setting a variable
提问by CuriousMind
I am writing a shell script where I am setting few variables, whose value is the output of commands.
我正在编写一个 shell 脚本,我在其中设置了几个变量,其值是命令的输出。
The errors I get are:
我得到的错误是:
$ $tag_name="proddeploy-$(date +"%Y%m%d_%H%M")"
-bash: =proddeploy-20141003_0500: command not found
now, I did read other similar questionsand based on it, I tried various things:
现在,我确实阅读了其他类似的问题,并在此基础上尝试了各种方法:
spliting command into two calls
将命令拆分为两个调用
$ $deploy_date=date +"%Y%m%d_%H%M"
bash: =date: command not found
$ $tag_name="proddeploy-$deploy_date"
bash: proddeploy- command not found
tried using backticks
尝试使用反引号
$ $tag_name=`proddeploy-$(date +"%Y%m%d_%H%M")`
bash: proddeploy-20141003_1734: command not found
bash: =: command not found
tried using $()
尝试使用 $()
$ $tag_name=$(proddeploy-$(date +"%Y%m%d_%H%M"))
bash: proddeploy-20141003_1735: command not found
bash: =: command not found
But in every case the command output is getting executed. how do I make it to stop executing command output and just store as a variable? I need this to work on ZSH and BASH.
但在每种情况下,命令输出都会被执行。如何让它停止执行命令输出并仅存储为变量?我需要它来处理 ZSH 和 BASH。
回答by fedorqui 'SO stop harming'
You define variables with var=string
or var=$(command)
.
您可以使用var=string
或定义变量var=$(command)
。
So you have to remove the leading $
and any other signs around =
:
因此,您必须删除前导$
和周围的任何其他标志=
:
tag_name="proddeploy-$(date +"%Y%m%d_%H%M")"
deploy_date=$(date +"%Y%m%d_%H%M")
^^ ^
From Command substitution:
从命令替换:
The second form
`COMMAND`
is more or less obsolete for Bash, since it has some trouble with nesting ("inner" backticks need to be escaped) and escaping characters. Use$(COMMAND)
, it's also POSIX!
`COMMAND`
对于 Bash 来说,第二种形式或多或少已经过时了,因为它在嵌套(“内部”反引号需要转义)和转义字符方面存在一些问题。使用$(COMMAND)
,也是POSIX!
Also, $()
allows you to nest, which may be handy.
此外,$()
允许您嵌套,这可能很方便。