4

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,

Kitcha
  • 1,641
  • 6
  • 19
  • 20
  • Are these args fixed strings (similar to `--help`, `--version`, etc.) or are they "anything"? – sarnold Mar 30 '12 at 23:43
  • Duplicate, http://stackoverflow.com/questions/255898/how-to-iterate-over-arguments-in-bash-script, http://stackoverflow.com/questions/4528292/passing-multiple-arguments-to-a-unix-shell-script – moodywoody Mar 30 '12 at 23:45
  • Yeah. I'm passing few flags as arguments to the script not necessarily in fixed numbers. – Kitcha Mar 30 '12 at 23:46

3 Answers3

5

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
ruakh
  • 175,680
  • 26
  • 273
  • 307
1

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.

chbrown
  • 11,865
  • 2
  • 52
  • 60
0

maybe this can help.

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

[ `echo $* | grep arg4` ] && echo true || echo false
Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
Umae
  • 445
  • 2
  • 5