https://stackoverflow.com/questions/2013547/assigning-default-values-to-shell-variables-with-a-single-command-in-bash/25895084
Very close to what you posted, actually:
FOO=${VARIABLE:-default} # If variable not set or null, use default.
Or, which will assign
default
to VARIABLE
as well:FOO=${VARIABLE:=default} # If variable not set or null, set it to default.
In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:
if ! type "$foobar_command_name" > /dev/null; then
# install foobar here
fi
For a real installation script, you'd probably want to be sure that type doesn't return successfully in the case when there is an alias foobar. In bash you could do something like this:
if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
# install foobar here
fi
This is preferable to
which
for a few reasons:
1) the default
which
implementations only support the -a
option that shows all options, so you have to find an alternative version to support aliases
2) type will tell you exactly what you are looking at (be it a bash function or an alias or a proper binary).
3) type doesn't require a subprocess
4) type cannot be masked by a binary (for example, on a linux box, if you create a program called
which
which appears in path before the real which
, things hit the fan. type
, on the other hand, is a shell built-in [yes, a subordinate inadvertently did this once]
Five ways, 4 for bash and 1 addition for zsh:
type foobar &> /dev/null
hash foobar &> /dev/null
command -v foobar &> /dev/null
which foobar &> /dev/null
(( $+commands[foobar] ))
(zsh only)
if [ "$T1" = "$T2" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi