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}"
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".
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.
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"
$_ (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.
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
.
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