I tried creating a var to do some operation in k8s. I intentionally put space between '=' and export and my cmd I want to shortcut. Why is linux shell giving me error?
export do = '--dry-run=client -o yaml'
-bash: export: `=': not a valid identifier
-bash: export: `--dry-run=client -o yaml': not a valid identifier
CodePudding user response:
The basic operation in shell is running a command. You do this by stating the name of the command, followed by an optional space-separated list of arguments. Every other bit of syntax follows from this.
export do = '--dry-run=client -o yaml' is just a call to the command export with 3 separate arguments. There is no assignment.
An assignment is a single word containing a single = that appears in an appropriate context. In the case of an export command, each of its argument is either:
- A valid identifier, on which the export attribute is set
- A valid assignment in the form
name=value, in which casenamereceives the export attribute and the valuevalueis assigned to the name.
As mentioned in the comments, it's better to use an array to store lists of arguments. (Note that you cannot export an array, nor do you likely need to export any name that's only going to be used in the shell, rather than looked for in the environment of a child process.)
do=(--dry-run=client -o yaml)
some_command "${do[@]}" # instead of some_command $do
CodePudding user response:
The reason why this doesn't work has to do with backwards-compliance for bash. The syntax you use on the CLI is the same on your would use on a shell script; shell scripts will always take the first word on each line and interpret them as commands.
Everything separated by a space after the command name will be interpreted as a space-separated list of arguments. Let's look at a simpler version of your export, as it's essentially setting your defined variable as an environment variable:
# This will evaluate to the command 'do' being executed with '='
# and '--dry-run=client -o yaml' being evaluated as arguments
do = '--dry-run=client -o yaml'
In order to circumvent that, Bash needs your variable assignments to be made without spaces. This way bash can lookup for any equal signs in your command and interpret them as assignments instead.
# Assigns the string '--dry-run=client -o ymal' to the variable 'do'
do='--dry-run=client -o yaml'
Since export just takes a variable assignment and turns it into a global environment variable, you need to follow the same convention:
export do='--dry-run=client -o yaml'
CodePudding user response:
Export works like every unix program:
program agr1 arg2
The args are separated via spaces, so in your case the args are:
arg1: "do"
arg2: "="
arg3: "'--dry-run=client -o yaml'"
and export can't handle this, because it is meaningless.
But if you try this:
export a='echo a' b='echo b'
the args will be:
arg1: "a='echo a'"
arg2: "b='echo b'"
and export knows this syntax.
