简体   繁体   English

Bash:检查是否给出了参数(例如,是否有参数“-a”?)

[英]Bash: Check if argument is given (e.g. is there the argument "-a" ?)

I have a script, which should accept 2 arguments.我有一个脚本,它应该接受 2 个参数。 (-s and -d). (-s 和 -d)。 If the -d argument is not given, i want to delete my debug file.如果没有给出 -d 参数,我想删除我的调试文件。 Same with -s.与 -s 相同。 How do I check if either $1 or $2 is -s or -d?如何检查 $1 或 $2 是 -s 还是 -d?

Shure with 2 arguments i could do that "Brute Force":舒尔有 2 个论据,我可以做到“蛮力”:

if test $1 != "-d" && test $2 != "-d" then
rm $debug
fi

But if I have more than 2 it will get complicated, so what is the proper way to check if any of the arguments is "-d" ?但是如果我有超过 2 个它会变得复杂,那么检查任何参数是否为 "-d" 的正确方法是什么?

Here's an oversimplified arguments parsing for you so you get the idea:这是为您解析的过度简化的参数,因此您明白了:

#!/bin/bash

arg_s=0
arg_d=0

show_help() { printf 'Help me\n'; }
show_version() { printf 'version -∞\n'; }
show_usage() { printf 'Usage: %s [-s|-d|-v|-h] [args...]\n' "${0##*/}"; }
invalid_option() { printf >&2 "you can't use option %s. You dumbo\n" "$1"; show_usage; exit 1; }

while (($#)); do
    [[ $1 = -- ]] && { shift; break; }
    [[ $1 = -?* ]] || break
    case $1 in
        (-s) arg_s=1 ;;
        (-d) arg_d=1 ;;
        (-h) show_help; exit 0 ;;
        (-v) show_version; exit 0 ;;
        (-*) invalid_option "$1" ;;
    esac
    shift
done

printf 'You passed the -s flag: %d\n' "$arg_s"
printf 'You passed the -d flag: %d\n' "$arg_d"
printf 'Remaining arguments:\n'
printf '   %s\n' "$@"

Note that it would need some extra work to handle flags like -ds that means -d -s 1 , a little bit of extra work to have options accepting parameters, and some extra work to handle long options.请注意,它需要一些额外的工作来处理像-ds这样的标志,这意味着-d -s 1 ,需要一些额外的工作来让选项接受参数,以及一些额外的工作来处理长选项。 All this is doable without any major problems.所有这些都是可行的,没有任何重大问题。


1 you can have a look at my mock which that has an argument parsing that supports that. 1你可以看看我的模拟which它有一个支持它的参数解析。

使用getopt(1)解析 shell 脚本中的命令行选项。

You can implement a basic loop as follow:您可以按如下方式实现基本循环:

for arg in "$@"; do
    if [ "$arg" = '-d' ]; then
        rm -f $debug
    fi
done

For more complex parsing, you should consider to use the builtin-command getopts对于更复杂的解析,您应该考虑使用内置命令 getopts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM