如何从命令中使用 getopts 获取文件名和参数
How can I get filename and argument with getopts from Command
这是代码,我要运行这个命令
获取test.log输入,然后将其转换为文本类型,然后存入output.txt文件
./small.sh test.log -t text -o output.txt
#!/usr/bin/env bash
usage() { echo "[=10=] usage:" && grep " .)\ #" [=10=]; exit 0; }
[ $# -eq 0 ] && usage
parse()
{
local file=
local type=
local output=
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
How can I get filename and argument with getopts
./small.sh test.log -t text -o output.txt
这是不可能的。 getopts
仅支持位置参数 after 选项参数。
您可以:
- 接受限制
- 使用其他东西,比如 GNU
getopt
。
- 编写自己的选项解析代码
这是代码,我要运行这个命令
获取test.log输入,然后将其转换为文本类型,然后存入output.txt文件
./small.sh test.log -t text -o output.txt
#!/usr/bin/env bash
usage() { echo "[=10=] usage:" && grep " .)\ #" [=10=]; exit 0; }
[ $# -eq 0 ] && usage
parse()
{
local file=
local type=
local output=
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
How can I get filename and argument with getopts
./small.sh test.log -t text -o output.txt
这是不可能的。 getopts
仅支持位置参数 after 选项参数。
您可以:
- 接受限制
- 使用其他东西,比如 GNU
getopt
。 - 编写自己的选项解析代码