chesnutp
chesnutp

Reputation: 53

Bash "-e" puzzler

I’m trying to build a command string based to pass in a “-e” flag and another variable into a another base script being call as a subroutine and have run into a strange problem; I’m losing the “-e” portion of the string when I pass it into the subroutine. I create a couple example which illustrate the issue, any help?

This works as you would expect:

$echo "-e  $HOSTNAME"

-e  ops-wfm

This does NOT; we lose the “-e” because it is interpreted as a special qualifier.

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

ops-wfm

Adding the “\” escape charactor doesn’t work either, I get the correct string with the "\" in front:

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

\-e ops-wfm

How can I prevent -e being swallowed?

Upvotes: 5

Views: 157

Answers (2)

johnsyweb
johnsyweb

Reputation: 141790

Use double-quotes:

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

I use ${var} rather than $var out of habit as it means that I can add characters after the variable without the 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

Upvotes: 5

larsks
larsks

Reputation: 311506

Well, you could put your variable in quotes:

echo "$myFlag"

...making it equivalent to your first example, which, as you say, works just fine.

Upvotes: 3

Related Questions