本文共 2037 字,大约阅读时间需要 6 分钟。
我需要检查输入参数的存在。 我有以下脚本
if [ "$1" -gt "-1" ] then echo hifi
我懂了
[: : integer expression expected
如何首先检查输入参数1是否存在?
检测参数是否传递给脚本的另一种方法:
((!$#)) && echo No arguments supplied!
注意(( expr ))
使表达式根据规则求值。
为了在没有任何参数的情况下退出,可以说:
((!$#)) && echo No arguments supplied! && exit 1
上面的另一种(类似)表达方式是:
let $# || echo No arguments suppliedlet $# || { echo No arguments supplied; exit 1; } # Exit if no arguments!
help let
说:
let: let arg [arg ...]
Evaluate arithmetic expressions. ... Exit Status: If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.
尝试:
#!/bin/bash if [ "$#" -eq "0" ] then echo "No arguments supplied" else echo "Hello world" fi
提醒一下,Bash中的数字测试运算符仅适用于整数( -eq
, -lt
, -ge
等)
我想确保我的$ vars是整数
var=$(( var + 0 ))
在测试它们之前,只是为了防止出现[[:必需的整数arg]错误。
最好以这种方式进行演示
if [[ $# -eq 0 ]] ; then echo 'some message' exit 1fi
如果参数太少,通常需要退出。
在某些情况下,您需要检查用户是否向脚本传递了参数,如果没有,则返回默认值。 就像下面的脚本一样:
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
且不为null时返回word
; 否则返回null。 如果要检查参数是否存在,可以检查参数#是否大于或等于目标参数编号。
以下脚本演示了它是如何工作的
#!/usr/bin/env bashif [ $# -ge 3 ]then echo script has at least 3 argumentsfi
产生以下输出
$ ./test.sh~$ ./test.sh 1~$ ./test.sh 1 2~$ ./test.sh 1 2 3script has at least 3 arguments$ ./test.sh 1 2 3 4script has at least 3 arguments
我经常将此代码段用于简单的脚本:
#!/bin/bashif [ -z "$1" ]; then echo -e "\nPlease call '$0' to run this command!\n" exit 1fi
只是因为有更多要指出的要点,我要补充一点,您可以简单地测试您的字符串是否为空:
if [ "$1" ]; then echo yeselse echo nofi
同样,如果您期望arg计数,只需测试您的最后一个:
if [ "$3" ]; then echo has args correct or notelse echo fixmefi
等等与任何arg或var
它是:
if [ $# -eq 0 ] then echo "No arguments supplied"fi
$#
变量将告诉您脚本传递的输入参数的数量。
或者您可以检查参数是否为空字符串,例如:
if [ -z "$1" ] then echo "No argument supplied"fi
-z
开关将测试“ $ 1”的扩展名是否为空字符串。 如果为空字符串,则执行主体。
转载地址:http://jtdnb.baihongyu.com/