12

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?

2
  • possible duplicate of bash shell script check input argument Commented Oct 11, 2013 at 8:12
  • @Thomas -- that checks if any argument exists -- I think this question asks if a specific argument exists Commented May 5, 2017 at 13:49

4 Answers 4

10

The simplest solution would be:

if [[ " $@ " =~ " -h " ]]; then echo "Has -h" fi 
Sign up to request clarification or add additional context in comments.

2 Comments

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>
true! Today I also would endorse getopts. The simple solution is more a wonky hack...
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.

3 Comments

The option is not removed. The trick to reparsing the argument list is to reset OPTIND=0 between the getopts loops.
Understood. Verified. Answer corrected. Thanks to Jonathan Leffler for all the tips that lead to this answer.
Note that for me this outputs "has -h" multiple times, even though -h was only specified once as an argument...
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.

Comments

0

I'm trying to solve this in a straightforward but correct manner, and am just sharing what works for me.

The dedicated function below solves it, which you can use like so:

if [ "$(has_arg "-h" "$@")" = true ]; then # TODO: code if "-h" in arguments else # TODO: code if "-h" not in arguments fi 

This function checks whether the first argument is in all other arguments:

function has_arg() { ARG="$1" shift while [[ "$#" -gt 0 ]]; do if [ "$ARG" = "$1" ]; then echo true return else shift fi done echo false } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.