Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash "-e" puzzler

Tags:

bash

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?

like image 952
chesnutp Avatar asked Nov 12 '11 01:11

chesnutp


2 Answers

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
like image 96
Johnsyweb Avatar answered Nov 06 '22 03:11

Johnsyweb


Well, you could put your variable in quotes:

echo "$myFlag"

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

like image 28
larsks Avatar answered Nov 06 '22 03:11

larsks