-1

I am writing a shell wrapper for a program. The wrapper will pass command line options to the program. Also it would supply (some) options if not specified.

Question is: how do I check if an option, say -j, is (not) in the argument list?

IF bash like python, I can do

if '-j' in $@; then
  my_prog "$@"
else
  my_prog "$@" -j 10
fi

obvious it is not.

How do I do it in bash, safely and elegantly ?

Thanks!

xyliu00
  • 726
  • 1
  • 9
  • 24
  • You can have a look at this question and my answer therein: http://stackoverflow.com/questions/28664721/bash-check-if-argument-is-given-e-g-is-there-the-argument-a – gniourf_gniourf Feb 25 '15 at 07:18

2 Answers2

1

A simple kludge is:

#!/bin/bash
if [[ " $* " == *" -j "* ]]
then
  echo "It contains -j"
fi

It concatenates all the arguments into a string and then checks if it contains " -j ".

You can also have a more robust version with a little more work:

inarray() {
  local element="$1"
  local f
  shift
  for f
  do 
    [[ "$f" == "$element" ]] && return 0
  done
  return 1
}

if inarray "-j" "$@"
then
  echo "It contains -j"
fi
that other guy
  • 116,971
  • 11
  • 170
  • 194
1

Another way, similar to that other guy's solution, also taking into account that there may be more than one option in arg, for e.g. -hijk, then -j will not exist, but j is still used:

#!/bin/bash

if $* | grep -o "j"
then
    joption=true
else
    joption=false
fi

Baring in mind this solution requires that no other argument has the letter "j" in it... :-)

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
asimovwasright
  • 838
  • 1
  • 11
  • 28