Kitcha
Kitcha

Reputation: 1731

How to process variable arguments to a shell script?

I would like to have my script accepting variable arguments. How do I check for them individually?

For example

./myscript arg1 arg2 arg3 arg4

 or 

./myscript arg4 arg2 arg3

The arguments can be any number and in any order. I would like to check if arg4 string is present or not irrespective of the argument numbers.

How do I do that?

Thanks,

Upvotes: 4

Views: 14521

Answers (3)

chbrown
chbrown

Reputation: 12028

This is playing fast and loose with the typical interpretation of command line "arguments", but I start most of my bash scripts with the following, as an easy way to add --help support:

if [[ "$@" =~ --help ]]; then
  echo 'So, lemme tell you how to work this here script...'
  exit
fi

The main drawback is that this will also be triggered by arguments like request--help.log, --no--help, etc. (not just --help, which might be a requirement for your solution).

To apply this method in your case, you would write something like:

[[ "$@" =~ arg4 ]] && echo "Ahoy, arg4 sighted!"

Bonus! If your script requires at least one command line argument, you can similarly trigger a help message when no arguments are supplied:

if [[ "${@---help}" =~ --help ]]; then
  echo 'Ok first yer gonna need to find a file...'
  exit 1
fi

which uses the empty-variable-substitution syntax ${VAR-default} to hallucinate a --help argument if absolutely no arguments were given.

Upvotes: 1

Umae
Umae

Reputation: 445

maybe this can help.

#!/bin/bash
# this is myscript.sh

[ `echo $* | grep arg4` ] && echo true || echo false

Upvotes: 0

ruakh
ruakh

Reputation: 183241

The safest way — the way that handles all possibilities of whitespace in arguments, and so on — is to write an explicit loop:

arg4_is_an_argument=''
for arg in "$@" ; do
    if [[ "$arg" = 'arg4' ]] ; then
        arg4_is_an_argument=1
    fi
done
if [[ "$arg4_is_an_argument" ]] ; then
    : the argument was present
else
    : the argument was not present
fi

If you're certain your arguments won't contain spaces — or at least, if you're not particularly worried about that case — then you can shorten that to:

if [[ " $* " == *' arg4 '* ]] ; fi
    : the argument was almost certainly present
else
    : the argument was not present
fi

Upvotes: 5

Related Questions