What does ":-" do in a variable declaration? - bash

I have been tasked with assuming control over some bash scripts, and looking through them I've come across the following notation:
INITPATH=${INITPATH:-"include"}
As far as I can tell this does something similar to a = a || b and allows the setting of a default value if the environment variable is not set?
I guess I'm just looking for some clarification on this, and whether the ":-" can be broken down or used in other contexts. I've as yet failed to come across it flicking through various Bash documentation.

From the manual:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted.
Otherwise, the value of parameter is substituted.
In your example, if INITPATH is unset/null, it's set to include.

This has most of how you can substitute
echo "$\{var}"
echo "Substitute the value of var."
echo "1 - $\{var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."
echo "2- $\{var:=word}"
echo "If var is null or unset, var is set to the value of word."
echo "5-$\{var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."
echo "3 - $\{var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."

Related

Conditional on non-instantiated variable

I am new to Bash scripting, having a lot more experience with C-type languages. I have written a few scripts with a conditional that checks the value of a non-instantiated variable and if it doesn't exist or match a value sets the variable. On top of that the whole thing is in a for loop. Something like this:
for i in ${!my_array[#]}; do
if [ "${my_array[i]}" = true ]
then
#do something
else
my_array[i]=true;
fi
done
This would fail through a null pointer in Java since my_array[i] is not instantiated until after it is checked. Is this good practice in Bash? My script is working the way I designed, but I have learned that just because a kluge works now doesn't mean it will work in the future.
Thanks!
You will find this page on parameter expansion helpful, as well as this one on conditionals.
An easy way to test a variable is to check it for nonzero length.
if [[ -n "$var" ]]
then : do stuff ...
I also like to make it fatal to access a nonexisting variable; this means extra work, but better safety.
set -u # unset vars are fatal to access without exception handling
if [[ -n "${var:-}" ]] # handles unset during check
then : do stuff ...
By default, referencing undefined (or "unset") variable names in shell scripts just gives the empty string. But is an exception: if the shell is run with the -u option or set -u has been run in it, expansions of unset variables are treated as errors and (if the shell is not interactive) cause the shell to exit. Bash applies this principle to array elements as well:
$ array=(zero one two)
$ echo "${array[3]}"
$ echo "array[3] = '${array[3]}'"
array[3] = ''
$ set -u
$ echo "array[3] = '${array[3]}'"
-bash: array[3]: unbound variable
There are also modifiers you can use to control what expansions do if a variable (or array element) is undefined and/or empty (defined as the empty string):
$ array=(zero one '')
$ echo "array[2] is ${array[2]-unset}, array[3] is ${array[3]-unset}"
array[2] is , array[3] is unset
$ echo "array[2] is ${array[2]:-unset or empty}, array[3] is ${array[3]:-unset or empty}"
array[2] is unset or empty, array[3] is unset or empty
There are a bunch of other variants, see the POSIX shell syntax standard, section 2.6.2 (Parameter Expansion).
BTW, you do need to use curly braces (as I did above) around anything other than a plain variable reference. $name[2] is a reference to the plain variable name (or element 0 if it's an array), followed by the string "[2]"; ${name[2]}, on the other hand, is a reference to element 2 of the array name. Also, you pretty much always want to wrap variable references in double-quotes (or include them in double-quoted strings), to prevent the shell from "helpfully" splitting them into words and/or expanding them into lists of matching files. For example, this test:
if [ $my_array[i] = true ]
is (mostly) equivalent to:
if [ ${my_array[0]}[i] = true ]
...which isn't what you want at all. But this one:
if [ ${my_array[i]} = true ]
still doesn't work, because if my_array[i] is unset (or empty) it'll expand to the equivalent of:
if [ = true ]
...which is bad test expression syntax. You want this:
if [ "${my_array[i]}" = true ]

What does +x mean in bash scripting [duplicate]

This question already has answers here:
What does "plus colon" ("+:") mean in shell script expressions?
(4 answers)
Closed 4 years ago.
What does +x mean in the below statement.
if[ -z ${FSV_ROOT+x} ]
Read up on Use Alternative Value. http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
In parameter expansion if parameter is unset or null, null shall be substituted; otherwise, the expansion of word shall be substituted. Use of the colon in the format shall result in a test for a parameter that is unset or null; omission of the colon shall result in a test for a parameter that is only unset.
So in your case:
If FSV_ROOT is set and not null, substitute x
If FSV_ROOT set but null, substitute x
If FSV_ROOT is unset, substitute null
${parameter+alt_value}: if parameter is set (to any value including null), return "alt_value" instead.
[ -z ${parameter+x} ] will return true if parameter has not been set at all. The "x" has no special meaning and could be replaced with any non-null string. It is there primarily because just [ -z $parameter ] would also return true if parameter were set to null - but it also helps to avoid a syntax error if $parameter were set to expand to more than one word, which would require quoting of the variable otherwise.
See also:
https://tldp.org/LDP/abs/html/parameter-substitution.html#PARAMALTV
http://tldp.org/LDP/abs/html/refcards.html
Do not confuse with the common use of +x with the chmod command, where it means to set the execute bit on a file.

Bash Automatically replacing [0:100] with 1

I'm writing a simple graphing script that uses gnuplot, and I use a helper function to construct a .gscript file.
add_gscript() {
echo "->>"
echo $1
echo $1 >> plot.gscript
cat plot.gscript
}
However after passing the following argument into the function
echo "--"
echo 'set xrange [0:$RANGE]'
echo "--"
add_gscript "set xrange [0:100]"
where $RANGE has been defined beforehand, I get the following output
--
set xrange [0:$RANGE]
--
->>
set xrange 1
set datafile separator ","
set term qt size 800,640
set size ratio .618
set xrange 1
Is bash evaluating [0:100] to 1 somehow?
A fix was accurately described in comments on the question:
Always double-quote variable references to have their values treated as literals; without quoting, the values are (in most contexts) subject to shell expansions, including word splitting and pathname expansion. [0:100] happens to be a valid globbing pattern that matches any file in the current dir. named either 0 or : or 1. – mklement0
so echo "$1"; echo "$1" >> plot.gscript and any other unquoted vars. Good luck. – shellter
Double quoting the variables did indeed fix my issue. Thanks!

How to make a script read a value from a property file and pass it to the same script?

I am new to linux shell script. i want that my script read a property file and save the value in any variable , the same which i can pass in same script..
as i wrote script is not fulfilling my requirement:
!/bin/bash
. test1
flat
if [ "$1" == test1 ]; then
flat=$1; /assign value to var flat
echo "flat"
fi
test1 is property file which includes :
la=12
tu=15
now i want when i run:
./myscript la
it read it from property file and store the value in flat variable.
Please help me.
You just need to use indirect referencing, but to do so, you need to store the value of the special parameter $1 in a regular parameter first.
!/bin/bash
. test1
var="$1"
# Only assign to flat if the variable specified in var is defined
if [ -n "${!var:-}" ]; then
flat="${!var}"; # assign value to var flat
echo "flat"
fi
First, ${!var} expands to the value of the variable whose name is in var. If var is "foo", it's the same as $foo. If var is "baz", it's the same as $baz.
${var:-default} expands to the value of var if it is set and has a non-null value. Otherwise, it expands to whatever you have after the ':-', in this case the string default. If there is no string, it uses the null value. So ${var:-} would expand to the null string if var was not set (or was already the null string).
Combining the two, ${!var:-} takes the variable var, and uses its value as a variable name. It then tries to expand that variable, and if it isn't set or is null, expand to the null string. So if var is la, it expands to the value of la. If var is re, and there is no variable re set, it expands to the null string.
Finally, the -n operator tests if its argument is non-zero length. In other words, it checks that the result of trying to expand the variable whose name is in var is not the null string. If that's true, then expand it again (yes, it's a little redundant) and assign its value to flat.
As the answer is written above, the variable flat is undefined if the argument to the script is not the name of a variable set in test1. If you don't mind flat being set regardless (say, flat=""), you don't need the if statement. You can just use one line to set the value of flat:
#!/bin/bash
. test1
var="$1"
flat="${!var:-}"
If I understood correctly you want to achieve an indirect variable dereferencing (see e.g. this example).
The solution is to use eval:
eval flat=\$$1

how to understand - and := in bash?

JOBS=${JOBS:="-j2"}
dir=${1-/usr/src}
What does := and - mean here?
I can guess they serve as some kind of default , what's the difference then?
For := (and the related =), you can use the built-in ':' command to just evaluate the parameter without having to assign it to itself:
# Set JOBS=-j2 if JOBS is not set or equal to ""
: ${JOBS:='-j2'}
# Set JOBS=-j2 if JOBS is not set. Don't change if JOBS is already set to ""
: ${JOBS='-j2'}
For :- and -, don't change the value of the variable; just use the second value in its place:
# Set dir to /usr/src if $1 is not set, but don't set $1 itself
dir=${1-/usr/src}
# Set dir to /usr/src if $1 is not set or set to "", but don't set or change $1
dir=${1:-/usr/src}
man bash (the Parameter Expansion section) will answer these and related questions.
Excerpt:
${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parame‐
ter is substituted.
${parameter:=word}
Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of
parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word
is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of
parameter is substituted.
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substi‐
tuted.

Resources