Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a string in bash only when the variable is defined and not null?

Tags:

bash

I want to obtain the following behaviour in bash and I have the impression that this is possible in one line but I don't know the exact syntax (and was not able to find it in the doc).

FOO=somename
BAR=123

If BAR is not defined or empty the final result should be just somename. If BAR has a value the final result should be somename-123

Current example is adding a dash even when BAR is not defined and that's not what I want.

echo "${FOO}-${BAR}"

like image 614
sorin Avatar asked Nov 23 '16 18:11

sorin


People also ask

How do I append a string to a variable in bash?

As of Bash version 3.1, a second method can be used to concatenate strings by using the += operator. The operator is generally used to append numbers and strings, and other variables to an existing variable. In this method, the += is essentially shorthand for saying "add this to my existing variable".

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.

How do I check if a variable is not empty in bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

From man bash:

   ${parameter:+word}
          Use Alternate Value.  If parameter is null or  unset,  nothing  is
          substituted, otherwise the expansion of word is substituted.

Example:

foo="somename"
bar="123"
echo "${foo}${bar:+-$bar}"

This prints somename-123. If you set bar="", it prints somename.

like image 78
that other guy Avatar answered Oct 02 '22 18:10

that other guy