【问题标题】:How can I get filename and argument with getopts from Command如何使用命令中的 getopts 获取文件名和参数
【发布时间】:2022-01-22 05:55:07
【问题描述】:

这是代码,我想运行这个命令
获取 test.log 输入,然后将其转换为 text 类型,然后将其存储在output.txt 文件

./small.sh test.log -t text -o output.txt

#!/usr/bin/env bash

usage() { echo "$0 usage:" && grep " .)\ #" $0; exit 0; }
[ $# -eq 0 ] && usage

parse()
{
        local file=$1
        local type=$2
        local output=$3

        echo "file: ${file}, type: ${type}, output: ${output}"
}

while getopts ":ht:o:" arg; do
  case $arg in
    t) # specify type.
      type=${OPTARG} ;;
    o) # specify directory.
      output=${OPTARG} ;;
    h | *) # Display help.
      usage
      exit 0
      ;;
  esac
done

shift $(( OPTIND - 1))
parse "${file}" "${type}" "${output}"

使用此代码,我只能在像这样将其按未排序顺序放置文件名时获取文件名 ./small.sh -t text -o output.txt test.log

【问题讨论】:

  • 常规顺序为./small.sh -t text -o output.txt test.log

标签: bash getopts


【解决方案1】:

如何使用 getopts 获取文件名和参数

./small.sh test.log -t text -o output.txt

这是不可能的。 getopts 仅支持位置参数 after 选项参数。

你可以:

  • 接受限制
  • 使用其他东西,例如 GNU getopt
  • 编写自己的选项解析代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2014-06-07
    • 1970-01-01
    相关资源
    最近更新 更多