简体   繁体   中英

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

I have a script, which should accept 2 arguments. (-s and -d). If the -d argument is not given, i want to delete my debug file. Same with -s. How do I check if either $1 or $2 is -s or -d?

Shure with 2 arguments i could do that "Brute Force":

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" ?

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. 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.

使用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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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