Shell 脚本:从命令行解析参数的方法

bgu*_*uiz 4 linux shell shell-script parsing parameters

myscript [-a a-arg] [-c c-arg] [-b] [-e] somedirectory
Run Code Online (Sandbox Code Playgroud)

鉴于我希望使用上述参数在命令行中调用我的 shell 脚本 - 其中 [这些括号] 表示它们是可选的 - 解析它们的最佳方法是什么?

Joh*_*n T 5

有几种方法可以解析命令行参数。假设您正在使用 bash,最不痛苦的方法可能是使用getopts.

例如:

#!/bin/bash
while getopts  "abc:" flag
do
  echo "$flag" $OPTIND $OPTARG
done
Run Code Online (Sandbox Code Playgroud)
[~]$./ssc.sh -ab -c 文件
1
乙 2
c 4 文件