This example shows how to create a bash function that will accept white space arguments. This doesn’t come up often but when it does I have to re-discover how to do it. This little reminder will make that rediscovery process unnecessary.
# Run a command.
# Decorate it with prefix and suffix information.
# Handle arguments with white space.
# Usage:
# runcmd git --nopager diff -stat
# runcmd git commit -a -m 'this is my commit message' file.ext
function runcmd() {
# Build the Cmd string from the input.
# Quote arguments that have embedded white space.
local Cmd=''
for Arg in "$@" ; do
if echo "$Arg" | grep ' ' 1>/dev/null ; then
Cmd="$Cmd '$Arg'"
else
Cmd="$Cmd $Arg"
fi
done
Cmd=${Cmd:1} # strip leading space
# Prefix.
echo ''
echo '# ================================================================'
echo "# Cmd: $Cmd"
echo "# Pwd: $(pwd)"
echo '# ================================================================'
# Execute the command.
eval time $Cmd
local Status=$?
# Suffix.
echo "# Status: $Status"
if (( $Status )) ; then
exit $Status
fi
return 0 # just in case the caller is checking
}