在Bash中使用空格大小写模式



我需要找到在case中使用模式中的空间的解决方案。我用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

参数"0624"用于从url下载文件的运行函数。参数"del-0624"用于删除本地机器中的文件。

问题:是否可能使用参数"del 0624"(带空格)?我对case中的参数中的空格有问题。

您需要在case中使用double quotes。此外,脚本应作为./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
  }

这是为了修改@Arjun的答案:

如果要匹配同一分支中的空格和通配符,只需在前面加一个即可转义空格。


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!

您可以设置自定义的IFS而不是默认的空格分隔符,以便解析包含空格的参数。

例如,这将用TAB替换所有脚本参数的-之前的空间,然后获取参数名称和值:

# 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 

相关内容

最新更新