我需要检查输入参数的存在。我有以下脚本

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

我明白了

[: : integer expression expected

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


当前回答

Try:

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

其他回答

Try:

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

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

#!/bin/bash

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

更现代

#!/usr/bin/env bash

if [[ $# -gt 0 ]]
  then echo Arguments were provided.
  else echo No arguments were provided.
fi

它是:

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

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

或者,您可以检查参数是否为空字符串或类似于:

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

z开关将测试“$1”的扩展是否为空字符串。如果它是空字符串,则执行主体。

作为一个小提示,Bash中的数字测试运算符只对整数(-eq、-lt、-ge等)有效

我希望通过以下方式确保我的$vars为int

var=$(( var + 0 ))

在我测试它们之前,只是为了防御“[:integer arg required”错误。