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?
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”.
$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.
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.
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.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With