Why Does Zsh Complain of My Variable Assignment as "Command Not Found"?
When I Try to Write a Zsh Script on macOS Big Sur, Version 11.5.1, I Noticed That It Keeps Failing to Recognize My Variables as Variables. Instead, Zsh Treats...
When I try to write a Zsh script on macOS Big Sur, Version 11.5.1, I noticed that it keeps failing to recognize my variables as variables.
Instead, Zsh treats them as UNIX-like commands.
In the screenshot linked above, I did the following on the Terminal application.
- Showed the contents of the simple Zsh shell script.
- Used the "ls -l" UNIX-like command to indicate its file permissions, and show that it is an executable Zsh shell script.
- Executed the Zsh shell script, which shows that the Zsh script interpreter complains of how my variable name is a "command not found".
The source code for my Zsh shell script is provided as follows:
#!/bin/zsh
unix_cmd = "ls -al"
Can you please kindly let me know what am I missing, and what did I do wrong?
I just want to assign values to variables in my Zsh shell scripts.
Thank you so much, and have a great day! Ciao!
1 Answer
The syntax to assign a value to a variable is foo=bar, not foo = bar. Whitespaces matter. The latter syntax is a command foo with arguments = and bar.
Few examples of how = is interpreted:
| code | meaning |
|---|---|
foo=bar |
proper assignment; now the value of foo is bar |
foo = bar |
command foo with arguments = and bar |
foo =bar |
command foo with one argument =bar |
foo= bar |
command bar with foo in its environment; the value of foo is empty |
foo=1 bar |
command bar with foo in its environment; the value of foo is 1 |
foo='1 bar' |
proper assignment; now the value of foo is 1 bar |
foo=' bar' |
proper assignment; now the value of foo is bar (note the leading space) |
foo=\ bar |
proper assignment; now the value of foo is bar (note the leading space) |
foo-x=bar |
command foo-x=bar (because foo-x is not a valid name for a shell variable) |
This is not specific to Zsh. The POSIX shell (sh) and POSIX-compliant shells behave this way. Zsh (while not being POSIX-compliant in general) also follows.