• Uncategorized

About linux : bash-command-not-found-when-setting-a-variable

Question Detail

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.

Question Answer

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.

The accepted answer shows corrected code, but does not clarify that one of your problems is accessing a variable (using $) while assigning it, which is illegal.
For example:


should be


See the difference? foo is being assigned, so you should not use $foo, which is not foo but the value of foo.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.