Bash test if an argument exists

11,004

Solution 1

The simplest solution would be:

if [[ " $@ " =~ " -h " ]]; then
   echo "Has -h"
fi

Solution 2

It is modestly complex. The quickest way is also unreliable:

case "$*" in
(*-h*) echo "Has -h";;
esac

Unfortunately that will also spot "command this-here" as having "-h".

Normally you'd use getopts to parse for arguments that you expect:

while getopts habcf: opt
do
    case "$opt" in
    (h) echo "Has -h";;
    ([abc])
        echo "Got -$opt";;
    (f) echo "File: $OPTARG";;
    esac
done

shift (($OPTIND - 1))
# General (non-option) arguments are now in "$@"

Etc.

Solution 3

#!/bin/bash
while getopts h x; do
  echo "has -h";
done; OPTIND=0

As Jonathan Leffler pointed out OPTIND=0 will reset the getopts list. That's in case the test needs to be done more than once.

Share:
11,004
Aleksandr Levchuk
Author by

Aleksandr Levchuk

Updated on October 16, 2022

Comments

  • Aleksandr Levchuk
    Aleksandr Levchuk over 1 year

    I want to test if an augment (e.g. -h) was passed into my bash script or not.

    In a Ruby script that would be:

    #!/usr/bin/env ruby
    puts "Has -h" if ARGV.include? "-h"
    

    How to best do that in Bash?

  • Jonathan Leffler
    Jonathan Leffler almost 13 years
    The option is not removed. The trick to reparsing the argument list is to reset OPTIND=0 between the getopts loops.
  • Aleksandr Levchuk
    Aleksandr Levchuk almost 13 years
    Understood. Verified. Answer corrected. Thanks to Jonathan Leffler for all the tips that lead to this answer.
  • logidelic
    logidelic almost 5 years
    Note that for me this outputs "has -h" multiple times, even though -h was only specified once as an argument...
  • Cecil Curry
    Cecil Curry about 3 years
    While clever, this reports false positives for arguments that are strings embedding the substring ` -h ` (e.g., my_command "oh gods -h game over"). The only general-purpose solution is to iterate getopts results as detailed below. </shrug>
  • kitingChris
    kitingChris about 3 years
    true! Today I also would endorse getopts. The simple solution is more a wonky hack...