使用getopts获取bash脚本的参数

时间:2017-02-13 13:57:45

标签: bash

我尝试制作一个脚本,首先我要获取参数。我正在使用getopts,但我无法使其工作: - (

#!/bin/bash

# evaluate entry args
# make args an array, not a string
args=( )

# replace long arguments
for arg; do
    case "$arg" in
        --dir)           args+=( -d ) ;;
        --quality)       args+=( -q ) ;;
        --size)          args+=( -s ) ;;
        --time)          args+=( -t ) ;;
        --help)          args+=( -h ) ;;
        *)               args+=( "$arg" ) ;;
    esac
done
printf 'args before update : '; printf '%q ' "$@"; echo
set -- "${args[@]}"
printf 'args after update  : '; printf '%q ' "$@"; echo

# init_variables

while getopts "d:q:s:t:h" OPTION; do
    : "$OPTION" "$OPTARG"
    echo "optarg : $OPTARG"
    case $OPTION in
    h)
      #usage
      exit 0
      ;;
    d)
      shift
      DIR=("$OPTARG")
      ;;
    q)
      shift
      QUALITY=("$OPTARG")
      ;;
    s)
      shift
      SIZE=("$OPTARG")
      ;;
    t)
      shift
      TIME=("$OPTARG")
      ;;      
    esac
done

echo "TIME=$TIME"
echo "DIR=$DIR"

如果我执行它,我只获得第一个参数(d或t,取决于顺序)。 我错过了什么?

./script.sh  -d dir -t 10
args before update : -d dir -t 10 
args after update  : -d dir -t 10 
optarg : dir
TIME=
DIR=dir

0 个答案:

没有答案