如何使用getopt(s)作为在bash中传递参数的技术

jda*_*mae 3 unix bash shell getopt getopts

有人能告诉我一个如何正确使用getopts的例子,或者我能够在参数中传递的任何其他技术吗?我试图在unix shell/bash中写这个.我看到有getopt和getopts,不知道哪个更好用.最后,我将构建它以添加更多选项.

在这种情况下,我想将文件路径作为输入传递给shell脚本,并在未正确输入的情况下放置描述.

export TARGET_DIR="$filepath"
Run Code Online (Sandbox Code Playgroud)

例如:(调用命令行)

./mytest.sh -d /home/dev/inputfiles
Run Code Online (Sandbox Code Playgroud)

如果以这种方式运行错误消息或提示正确使用:

./mytest.sh -d /home/dev/inputfiles/
Run Code Online (Sandbox Code Playgroud)

gle*_*man 6

作为一个用户,我会非常恼火的一个程序,它给我一个错误,提供一个带有斜杠的目录名称.如有必要,您可以将其删除.

一个shell示例,包含非常完整的错误检查:

#!/bin/sh

usage () {
  echo "usage: $0 -d dir_name"
  echo any other helpful text
}

dirname=""
while getopts ":hd:" option; do
  case "$option" in
    d)  dirname="$OPTARG" ;;
    h)  # it's always useful to provide some help 
        usage
        exit 0 
        ;;
    :)  echo "Error: -$OPTARG requires an argument" 
        usage
        exit 1
        ;;
    ?)  echo "Error: unknown option -$OPTARG" 
        usage
        exit 1
        ;;
  esac
done    

if [ -z "$dirname" ]; then
  echo "Error: you must specify a directory name using -d"
  usage
  exit 1
fi

if [ ! -d "$dirname" ]; then
  echo "Error: the dir_name argument must be a directory
  exit 1
fi

# strip any trailing slash from the dir_name value
dirname="${dirname%/}"
Run Code Online (Sandbox Code Playgroud)

有关getopts文档,请查看bash手册