Bash test if an argument exists

2019-06-17 06:41发布

问题:

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?

回答1:

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.



回答2:

#!/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:

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

See my function mt() below for an example usage:

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


回答4:

The simplest solution would be:

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