首页 文章

检查Bash shell脚本中是否存在输入参数

提问于
浏览
989

我需要检查输入参数是否存在 . 我有以下脚本

if [ "$1" -gt "-1" ]
  then echo hi
fi

我明白了

[: : integer expression expected

如何首先检查输入参数1以查看它是否存在?

9 回答

  • 243

    它是:

    if [ $# -eq 0 ]
      then
        echo "No arguments supplied"
    fi
    

    $# 变量将告诉您脚本传递的输入参数的数量 .

    或者您可以检查参数是否为空字符串或不是:

    if [ -z "$1" ]
      then
        echo "No argument supplied"
    fi
    

    -z 开关将测试"$1"的扩展是否为空字符串 . 如果它是一个空字符串,则执行正文 .

  • 76

    最好以这种方式展示

    if [[ $# -eq 0 ]] ; then
        echo 'some message'
        exit 1
    fi
    

    如果参数太少,通常需要退出 .

  • 29

    我经常将此代码段用于简单脚本:

    #!/bin/bash
    
    if [ -z "$1" ]; then
        echo -e "\nPlease call '$0 <argument>' to run this command!\n"
        exit 1
    fi
    
  • 3

    作为一个小提醒,Bash中的数值测试运算符仅适用于整数( -eq-lt-ge 等)

    我想确保我的$ vars是完整的

    var=$(( var + 0 ))
    

    在我测试它们之前,只是为了防止“[:所需的整数arg”错误 .

  • 15

    如果您想检查参数是否存在,可以检查参数的数量是否大于或等于目标参数号 .

    以下脚本演示了这是如何工作的

    test.sh

    #!/usr/bin/env bash
    
    if [ $# -ge 3 ]
    then
      echo script has at least 3 arguments
    fi
    

    产生以下输出

    $ ./test.sh
    ~
    $ ./test.sh 1
    ~
    $ ./test.sh 1 2
    ~
    $ ./test.sh 1 2 3
    script has at least 3 arguments
    $ ./test.sh 1 2 3 4
    script has at least 3 arguments
    
  • 5

    尝试:

    #!/bin/bash
     if [ "$#" -eq  "0" ]
       then
         echo "No arguments supplied"
     else
         echo "Hello world"
     fi
    
  • 1748

    如果您只想检测某个参数是否缺失,parameter substitution很棒:

    #!/bin/bash
    # usage-message.sh
    
    : ${1?"Usage: $0 ARGUMENT"}
    #  Script exits here if command-line parameter absent,
    #+ with following error message.
    #    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT
    

    在某些情况下,您需要检查用户是否将参数传递给脚本,如果不是,则回退到默认值 . 如下面的脚本:

    scale=${2:-1}
    emulator @$1 -scale $scale
    

    如果用户没有将 scale 作为第二个参数传递,我默认启动带有 -scale 1 的Android模拟器 . ${varname:-word} 是一个扩展运营商 . 还有其他扩展运营商:

    • ${varname:=word} 设置未定义的 varname 而不是返回 word 值;

    • ${varname:?message} 如果已定义且返回 varname 并且不为null或打印 message 并中止脚本(如第一个示例);

    • ${varname:+word} 仅在 varname 定义且不为空时才返回 word ;否则返回null .

  • 3

    另一种检测参数是否传递给脚本的方法:

    ((!$#)) && echo No arguments supplied!
    

    请注意 (( expr )) 会导致根据Shell Arithmetic的规则计算表达式 .

    为了在没有任何论据的情况下退出,可以说:

    ((!$#)) && echo No arguments supplied! && exit 1
    

    另一种(类似的)说上述方式是:

    let $# || echo No arguments supplied
    
    let $# || { echo No arguments supplied; exit 1; }  # Exit if no arguments!
    

    help let 说:

    let:let arg [arg ...]计算算术表达式 .

    ...

    退出状态:
    如果最后一个ARG的计算结果为0,则返回1;让我们返回0 .

  • 29

    只是因为有一个更基点指出我会补充说你可以简单地测试你的字符串为null:

    if [ "$1" ]; then
      echo yes
    else
      echo no
    fi
    

    同样,如果你期待arg计数只是测试你的最后一次:

    if [ "$3" ]; then
      echo has args correct or not
    else
      echo fixme
    fi
    

    等等任何arg或var

相关问题