Bash "-e" puzzler

I am trying to create a command line based on the transfer in the "-e" flag, and another variable to another script base, calling as a subroutine, and ran into some strange problem; I lose the "-e" part of the line when I pass it to the subroutine. I am creating a couple of examples illustrating the problem, any help?

This works as you expected:

$echo "-e $HOSTNAME" -e ops-wfm 

Is not; we lose "-e" because it is interpreted as a special classifier.

 $myFlag="-e $HOSTNAME"; echo $myFlag ops-wfm 

Adding the character "\" escape also does not work, I get the correct line with "\" in front:

 $myFlag="\-e $HOSTNAME"; echo $myFlag \-e ops-wfm 

How to prevent swallowing -e ?

+4
source share
2 answers

Use double quotes:

 $ myFlag="-e $HOSTNAME"; echo "${myFlag}" -e myhost.local 

I use ${var} and not $var out of habit, as this means that I can add characters after a variable without a shell, interpreting them as part of the variable name.

echo may not be the best example here. Most Unix commands will accept -- to mark no more switches .

 $ var='-e .bashrc' ; ls -l -- "${var}" ls: -e .bashrc: No such file or directory 
+4
source

Well, you can put your variable in quotation marks:

 echo "$myFlag" 

... which makes it equivalent to your first example, which, as you say, works very well.

+3
source

Source: https://habr.com/ru/post/1380873/


All Articles