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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# 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 } |