Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: echo string that starts with "-"

VAR="-e xyz" echo $VAR 

This prints xyz, for some reason. I don't seem to be able to find a way to get a string to start with -e.

What is going on here?

like image 311
miracle2k Avatar asked Sep 06 '10 15:09

miracle2k


People also ask

How do you check if a string starts with a letter in bash?

We can use the double equals ( == ) comparison operator in bash, to check if a string starts with another substring. In the above code, if a $name variable starts with ru then the output is “true” otherwise it returns “false”.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is echo $$ in bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


2 Answers

The answers that say to put $VAR in quotes are only correct by side effect. That is, when put in quotes, echo(1) receives a single argument of -e xyz, and since that is not a valid option string, echo just prints it out. It is a side effect as echo could just as easily print an error regarding malformed options. Most programs will do this, but it seems GNU echo (from coreutils) and the version built into bash simply echo strings that start with a hyphen but are not valid argument strings. This behaviour is not documented so it should not be relied upon.

Further, if $VAR contains a valid echo option argument, then quoting $VAR will not help:

$ VAR="-e" $ echo "$VAR"  $ 

Most GNU programs take -- as an argument to mean no more option processing — all the arguments after -- are to be processed as non-option arguments. bash echo does not support this so you cannot use it. Even if it did, it would not be portable. echo has other portability issues (-n vs \c, no -e).

The correct and portable solution is to use printf(1).

printf "%s\n" "$VAR" 
like image 90
camh Avatar answered Oct 08 '22 08:10

camh


The variable VAR contains -e xyz, if you access the variable via $ the -e is interpreted as a command-line option for echo. Note that the content of $VAR is not wrapped into "" automatically.

Use echo "$VAR" to fix your problem.

like image 20
heb Avatar answered Oct 08 '22 10:10

heb