Bash check if argument exists

I want to check if an addition (e.g. -h) has been added to my bash script or not.

In a Ruby script that will be:

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

What is the best way to do this in Bash?

+7
source share
4 answers

This is modestly complicated. The fastest way is also unreliable:

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

Unfortunately, this also indicates " command this-here " as having " -h ".

Normally you should use getopts to parse the arguments 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.

+3
source
 #!/bin/bash while getopts hx; do echo "has -h"; done; OPTIND=0 

As Jonathan Leffler noted, OPTIND = 0 will reset the list of getopts. This is if the test needs to be performed several times.

+1
source

I found the answer in this question: https://serverfault.com/questions/7503/how-to-determine-if-a-bash-variable-is-empty

For an example of using my mt () function below:

  # mkdir -p path to touch file mt() { if [[ -z $1 ]]; then echo "usage: mt filepath" else mkdir -p `dirname $1` touch $1 fi } 
+1
source

The simplest solution:

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

All Articles