Wednesday, November 4, 2009

Bash variable assigment modifiers

I always seem to forget this about bash variable assignment shortcuts and always have a hard time finding it.

Rather than:

if [ "" = "$var" ]; then
$var=hello
fi

Use
var=${var:-hello}

Conversely, rather than:
if [ "" != "$var" ]; then
$var=hello
fi

Use
var=${var:+hello}

There's also:
if [ "" = "$var" ]; then
echo "Error, variable var must be set"
else
b=$var
fi

And:
b=${var:?Error, variable var must be set}


There are others too, but I find these ones most useful. Check bash man page for full set.

No comments: