小编St3*_*3an的帖子

如何使用 getopts 正确解析 shell 脚本标志和参数

我正在使用这个:

例如 ./imgSorter.sh -d directory -f format

脚本的内容是:

#!/bin/bash
while getopts ":d:f:" opt; do
  case $opt in
    d)
      echo "-d was triggered with $OPTARG" >&2
      ;;
    f)
      echo "-f was triggered with $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
Run Code Online (Sandbox Code Playgroud)

用例 :

$ ./imgSorter.sh -d myDir -d was triggered with myDir 好的

$ ./imgSorter.sh -d -f myFormat -d was triggered with -f NOK:以 …

shell bash options getopts arguments

2
推荐指数
1
解决办法
2万
查看次数

标签 统计

arguments ×1

bash ×1

getopts ×1

options ×1

shell ×1