Bash 测试参数是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6221271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:06:53  来源:igfitidea点击:

Bash test if an argument exists

bashtestingcommand-line-arguments

提问by Aleksandr Levchuk

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

我想测试是否将增强(例如 -h)传递到我的 bash 脚本中。

In a Ruby script that would be:

在 Ruby 脚本中:

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

How to best do that in Bash?

如何在 Bash 中最好地做到这一点?

回答by Jonathan Leffler

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".

不幸的是,这也会发现“ command this-here”具有“ -h”。

Normally you'd use getoptsto parse for arguments that you expect:

通常你会getopts用来解析你期望的参数:

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.

等等。

回答by kitingChris

The simplest solution would be:

最简单的解决方案是:

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

回答by Aleksandr Levchuk

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

正如 Jonathan Leffler 指出的那样 OPTIND=0 将重置 getopts 列表。以防万一测试需要进行多次。

回答by keyvan

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

我在这里找到了一个欺骗性问题的答案:https: //serverfault.com/questions/7503/how-to-determine-if-a-bash-variable-is-empty

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

有关示例用法,请参阅下面的函数 mt():

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