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.
Written by William Kelly
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Shell
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#