bash command not found when setting a variable

泄露秘密 提交于 2019-11-26 11:43:14

问题


I am writing a shell script where I am setting few variables, whose value is the output of commands.

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 questions and 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.


回答1:


You define variables with var=string or 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!

Also, $() allows you to nest, which may be handy.



来源:https://stackoverflow.com/questions/26178654/bash-command-not-found-when-setting-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!