Last Updated: February 25, 2016
·
930
· willkelly

Variable setting tricks

Set a variable to a default value if unset.

SOMEVAR="somevalue"
SOMEVAR=${SOMEVAR:-default_value}
# echo "somevalue"
echo $SOMEVAR

unset SOMEVAR
SOMEVAR=${SOMEVAR:-default_value}
# echos default_value
echo $SOMEVAR 

Remove a prefix from the value of a variable.

SOMEVAR="default_value"
# echo "value"
echo ${SOMEVAR#default_} 
# also echo "value"
echo ${SOMEVAR#*_} 

Remove a suffix from the value of a variable

SOMEVAR="file.extension"
# echo 'file'
echo ${SOMEVAR%.*} 

Perform pattern substitution on a variable

SOMEVAR="file.extension"
# cp file.extension file.bak
cp $SOMEVAR ${SOMEVAR/extension/bak}

I find these tricks helpful when writing shell scripts and one-liners.