Bash test if an argument exists

2019-06-17 06:00发布

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?

4条回答
beautiful°
2楼-- · 2019-06-17 06:43

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
      }
查看更多
神经病院院长
3楼-- · 2019-06-17 06:44
#!/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.

查看更多
太酷不给撩
4楼-- · 2019-06-17 06:45

The simplest solution would be:

if [[ " $@ " =~ " -h " ]]; then
   echo "Has -h"
fi
查看更多
看我几分像从前
5楼-- · 2019-06-17 06:59

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.

查看更多
登录 后发表回答