Convenient shell idiom for reverse "use of alternative meaning"

I was looking for a quick icon POSIX shell, which performs the inverse expression ${VARIABLE:+word}"use of alternative values" .

That is, when VARIABLE is null or unset, I want a word, but when VARIABLE is not null, I want null.

For example, if I have a shell variable FLAG_VERBOSE, I can easily make ordinary silent commands more verbose if this variable is non-zero:

some_quiet_cmd ${FLAG_VERBOSE:+ --verbose} arg arg arg ... # verbose only if $FLAG_VERBOSE is set

However, when I have a regular chat command, I want to suppress its normal chatter when FLAG_VERBOSE is not set by setting an argument:

if [ "$FLAG_VERBOSE" ]; then
  CHATTINESS=
else
  CHATTINESS=--quiet
fi

some_chatty_cmd $CHATTINESS arg arg arg ... # --quiet unless $FLAG_VERBOSE is set

? , ${VARIABLE:!word} . (, " "?)

+4
4

, :

some_chatty_cmd $( [ "$FLAG_VERBOSE" ] || echo --quiet ) arg... # default --quiet
#               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+1

- :

~.$ blank_or () { [[ $# -lt 2 ]] && { echo blank_or "\$var" default 1>&2; return 1; }; [[ "$1" = "" ]] && echo $2; }
~.$ this=that; blank_or "$this" --quiet
~.$ this=; blank_or "$this" --quiet
--quiet
~.$ blank_or
blank_or $var default
~.$ 

, , . :

some_chatty_cmd $(blank_or "$FLAG_VERBOSE" --quiet) arg arg arg ...
+2

, . .

. --verbose --quiet GNU, Id :

if test -n "$FLAG_VERBOSE"; then
    v=--verbose
    q=
else
    v=
    q=--quiet
fi

$v $q .

+1
source

You can use this:

if [ -n "$FLAG_VERBOSE" ]; then CHATTINESS=; else CHATTINESS=--quiet; fi

some_chatty_cmd $CHATTINESS ${FLAG_VERBOSE:+ --verbose} arg arg arg
0
source

Source: https://habr.com/ru/post/1568217/


All Articles