1

I want to check if a command line option exists when running a shell script, example

./test.sh arg1 arg2 arg3 arg4

Want to check if one of the argument is say arg3 (not necessarily the third argument)

The quick solution is to use a for loop and check if one of the argument matches a given string, but is there a better way to do it something of the form 'arg3' in $@.

1 Answer 1

2

(assuming bash)

I would do this:

have_arg3=false
for arg; do
    if [[ $arg == "arg3" ]]; then
        have_arg3=true
        break
    fi
done
if $have_arg3; then
    echo "arg3 is present
fi

but you could do this (all quotes and spaces below are required!):

if [[ " $* " == *" arg3 "* ]]; then
    echo "arg3 is present"
fi

can be encapsulated in a function:

$ arg_in_args () (
    arg=$1
    shift
    IFS=:
    [[ "$IFS$*$IFS" == *"$IFS$arg$IFS"* ]]
)
$ set -- foo bar baz
$ if arg_in_args "arg3" "$@"; then echo Y; else echo N; fi
N
$ if arg_in_args "baz" "$@"; then echo Y; else echo N; fi
Y
Sign up to request clarification or add additional context in comments.

1 Comment

The first solution will work; the second solution may not work if arguments can contain spaces (or whatever you try to use to separate arguments).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.