我需要检查输入参数是否存在.我有以下脚本
if [ "$1" -gt "-1" ]
then echo hi
fi
Run Code Online (Sandbox Code Playgroud)
我明白了
[: : integer expression expected
Run Code Online (Sandbox Code Playgroud)
如何首先检查输入参数1以查看它是否存在?
pho*_*xis 2114
它是:
if [ $# -eq 0 ]
then
echo "No arguments supplied"
fi
Run Code Online (Sandbox Code Playgroud)
该$#
变量将告诉您脚本传递的输入参数的数量.
或者您可以检查参数是否为空字符串或不是:
if [ -z "$1" ]
then
echo "No argument supplied"
fi
Run Code Online (Sandbox Code Playgroud)
该-z
开关是检验的"$ 1"的扩张是一个空字符串或没有.如果它是一个空字符串,则执行正文.
小智 313
最好以这种方式进行演示
if [[ $# -eq 0 ]] ; then
echo 'some message'
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
如果参数太少,通常需要退出.
Ale*_* N. 94
如果您只想检测是否缺少特定参数,则参数替换很好:
scale=${2:-1}
emulator @$1 -scale $scale
Run Code Online (Sandbox Code Playgroud)
在某些情况下,您需要检查用户是否将参数传递给脚本,如果没有,则返回默认值.如下面的脚本:
scale=${2:-1}
emulator @$1 -scale $scale
Run Code Online (Sandbox Code Playgroud)
这里如果用户没有scale
作为第二个参数传递,我-scale 1
默认启动Android模拟器.${varname:-word}
是一家扩张运营商.还有其他扩展运营商:
${varname:=word}
其中设置所述未定义varname
的而不是返回word
值;${varname:?message}
varname
如果它被定义并且不为null则返回,或者打印message
并中止脚本(如第一个例子);${varname:+word}
返回word
如果只varname
被定义并且不为空; 否则返回null.Ran*_*r T 39
尝试:
#!/bin/bash
if [ "$#" -eq "0" ]
then
echo "No arguments supplied"
else
echo "Hello world"
fi
Run Code Online (Sandbox Code Playgroud)
dev*_*ull 36
另一种检测参数是否传递给脚本的方法:
((!$#)) && echo No arguments supplied!
Run Code Online (Sandbox Code Playgroud)
请注意,这(( expr ))
会导致根据Shell算法的规则计算表达式.
为了在没有任何论据的情况下退出,可以说:
((!$#)) && echo No arguments supplied! && exit 1
Run Code Online (Sandbox Code Playgroud)
另一种(类似的)说上述方式是:
let $# || echo No arguments supplied
let $# || { echo No arguments supplied; exit 1; } # Exit if no arguments!
Run Code Online (Sandbox Code Playgroud)
help let
说:
let: let arg [arg ...]
Run Code Online (Sandbox Code Playgroud)Evaluate arithmetic expressions. ... Exit Status: If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.
小智 22
我经常将此代码段用于简单脚本:
#!/bin/bash
if [ -z "$1" ]; then
echo -e "\nPlease call '$0 <argument>' to run this command!\n"
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
Ser*_*ndt 22
#!/usr/bin/env bash
if [[ $# -gt 0 ]]
then echo Arguments were provided.
else echo No arguments were provided.
fi
Run Code Online (Sandbox Code Playgroud)
小智 16
只是因为有更多的基点要指出我会添加你可以简单地测试你的字符串为null:
if [ "$1" ]; then
echo yes
else
echo no
fi
Run Code Online (Sandbox Code Playgroud)
同样,如果你期待arg计数只是测试你的最后一次:
if [ "$3" ]; then
echo has args correct or not
else
echo fixme
fi
Run Code Online (Sandbox Code Playgroud)
等等任何arg或var
如果您想检查参数是否存在,您可以检查参数# 是否大于或等于您的目标参数编号。
以下脚本演示了这是如何工作的
#!/usr/bin/env bash
if [ $# -ge 3 ]
then
echo script has at least 3 arguments
fi
Run Code Online (Sandbox Code Playgroud)
产生以下输出
$ ./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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1132448 次 |
最近记录: |