skyndas
skyndas

Reputation: 265

Using space in case pattern in Bash

I need find solution for using space in pattern in case. I have this function with case

  setParam() {
    case "$1" in
          0624)
            # do something - download file from url
          ;;
          del-0624)
            # do something - delete file from local machine
            exit 0
          ;;
      # Help
          *|''|h|help)
            printHelp
            exit 0
          ;;
    esac
  }

  for PARAM in $*; do
    setParam "$PARAM"
  done

Paramter "0624" is for run function for download files from url. Paramter "del-0624" is for deleting files in local machine.

Question: It is possible use paramter "del 0624"(with space)? I have problem with space in parameter in case.

Upvotes: 9

Views: 9603

Answers (3)

cyqsimon
cyqsimon

Reputation: 3735

This is to amend @Arjun's answer:

If you want to match spaces and wildcards in the same branch, simply escape the space by prepending a \.


test.sh:

#!/usr/bin/env bash
case "$1" in
    foo\ *)
        echo "matched!" ;;
    *)
        echo "not matched!" ;;
esac

$ ./test.sh "foo bar"
matched!
$ ./test.sh "foobar"
not matched!

Upvotes: 2

Noam Manos
Noam Manos

Reputation: 16980

You can set a custom IFS instead of the default space delimiter, in order to parse parameters that include spaces.

For example, this will replace the space before the - of all the script parameters with a TAB, and then grab the parameter name and value:

# Get script parameters, and split by tabs instead of space (for IFS)
SCRIPT_PARAMS="$*"
SCRIPT_PARAMS=${SCRIPT_PARAMS// -/$'\t'-}
IFS=$'\t'

for param in ${SCRIPT_PARAMS} ; do
  # Get the next parameter (flag) name, without the value
  param_name=${param%% *} 
  # Get the parameter value after the flag, without surrounding quotes
  param_value=$(echo "${param#*"$param_name" }" | xargs)
  
  case $param_name in
  -b|--basic)
    echo "Parse a basic parameter '${param_name}' without a value"
    shift ;; # After a basic parameter shift just once
  -c|--custom)
    echo "Parse a custom parameter '${param_name}' with value of: ${param_value}"
    shift 2 ;; # After a custom parameter shift twice
  -*)
    echo "Error - unrecognized parameter: ${param}" 1>&2
    exit 1 ;;
  *)
    break ;;
  esac
done

# Reset IFS
unset IFS 

Upvotes: 0

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

You need to use double quotes in case. Also script should be run as ./script "del 0624".

setParam() {
    case "$1" in
          "0624")
            # do something - download file from url
          ;;
          "del-0624")
            # do something - delete file from local machine
            exit 0
          ;;
          "del 0624")
            # do something - delete file from local machine
            exit 0
          ;;
      # Help
          *|''|h|help)
            printHelp
            exit 0
          ;;
    esac
  }

Upvotes: 14

Related Questions