The only way to make a variable expansion disappear is by having the expansion expand to an empty value when that expansion is unquoted.
$ unset a; b=''; c=set
$ printf '<%s> ' unquoted $a $b quoted "$a" "$b" val $c "$c"; echo
<unquoted> <quoted> <> <> <val> <s> <t> <set>
Both unset and empty values of a variable (a
and b
) disappear (as arguments) when unquoted. Both are retained when quoted.
Furthermore, even spaces (or any character) will disappear if included in IFS.
$ IFS=' '
$ unset a; b=' '; c=' set '
$ printf '<%s> ' unquoted $a $b quoted "$a" "$b" val $c "$c"; echo
<unquoted> <quoted> <> < > <val> <set> < set >
In fact, an IFS that contains characters in the value to expand (unquoted) will separate arguments.
$ IFS='e '
$ $ printf '<%s> ' unquoted $a $b quoted "$a" "$b" val $c "$c"; echo
<unquoted> <quoted> <> < > <val> <s> <t> < set >
Note the two arguments <s>
and <t>
which resulted from expanding the value set
when IFS contained e
.
So, we need an unquoted expansion of unset or empty values which becomes a quoted expansion of the value when there is a value to expand:
${var:+"$var"}
Description:
${ # starts an un-quoted variable expansion
var # name of variable to expand
: # also replace if var is null
+ # use what follows if is not unset (nor null)
"$var" # a quoted variable expansion.
} # end of expansion.
# In short: expand "$var" if it has a value, $var otherwise.
We can then use $1
value to either disappear it or expand it
echo ${1:+"--noise"} ${1:+"$1"}
The line above will either print two separate arguments (not affected by IFS) if $1
has some (not null) value or nothing if $1
is empty or unset.
The script will become:
#!/bin/sh
echo "Noise $1"
echo "Enhancement $2"
for snr in 0 5 10 15 20 25
do python evaluate.py \
${1:+"--noise"} ${1:+"$1"} \
--snr "$snr" \
--iterations 1250 \
${2:+"--enhancement"} ${2:+"$2"}
done
This solution is not affected by the value of IFS
snr
inside for loop ? – Archemar Jan 19 '20 at 13:13--snr "$snr"
? – Barmar Jan 20 '20 at 02:21