Bash function that accepts white space arguments

SysAdminTechnology



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.

# 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
}

Trackbacks

Trackback specific URI for this entry

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Submitted comments will be subject to moderation before being displayed.

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Gravatar, Twitter, Pavatar, Identica author images supported.
Markdown format allowed