Linux Bash: Command not found error in variable assignment - chaitanyavangalapudi/devops-scripts GitHub Wiki

Code snippet

script.sh

#! /bin/bash

now = $(date +"%d_%m_%Y");
echo $now;

throws error when run

./script.sh: line 3: 27_03_2019: command not found

To solve this problem, remove spaces surrounding your assignment.

#! /bin/bash

now=$(date +"%d_%m_%Y");
echo $now;

Scenario #1 When you write: STR = "foo"

bash tries to run a command named STR with 2 arguments (the strings '=' and 'foo')

Scenario #2 When you write: STR =foo

bash tries to run a command named STR with 1 argument (the string '=foo')

Scenario #3 When you write: STR= foo

bash tries to run the command foo with STR set to the empty string in its environment.

  • The first command is exactly equivalent to: STR "=" "foo"
  • The second is the same as STR "=foo"
  • Tnd the last is equivalent to STR="" foo

References: