在if语句和函数中重击多个条件 [英] Bash Multiple Conditions in If Statement and Functions

查看:87
本文介绍了在if语句和函数中重击多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查参数个数是否为1,以及我之前在脚本中编写的函数是否为true,但不起作用:

I'm trying to check if the number of arguments is one and if functions that I wrote in my script previously are true , but it does not work:

if [ $# -eq 1 && echo "$1" | lgt && echo "Invalid Length - $1" && echo "$1" | checking_another_function_etc ]; then
echo "some output" && exit 1

"lgt"是函数名称.

"lgt" is a function name.

我正在尝试使用(([[[[引号,多个if语句,但是它也不起作用.也许我应该用引号分隔参数检查和函数的数量,但是我不确定该怎么做.我想知道是否甚至可以将echo命令传递到if条件.

I was trying to use (( [[ [ quotes, multiple if statements but it didn't work either. Maybe I should separate the number of arguments checking and functions with quotes, but I'm not sure how to do it. I'm wondering if it is even possible to pass echo command to if condition.

问题是,在检查完所有功能之后,我需要一个echo语句,但是在每个功能之后,我都需要自己的echo语句.

The thing is I need one echo statement after checking of all functions, but after each function I need its own echo statement.

推荐答案

[是普通命令(也拼写为test); [/]对不能简单地包围命令列表.仅-eq表达式由[求值;其他是由外壳&&运算符加入的单独命令.

[ is an ordinary command (also spelled test); the [/] pair cannot simply surround a command list. Only the -eq expression is evaluated by [; the others are separate commands joined by the shell && operator.

if [ $# -eq 1 ] &&
   echo "$1" | lgt &&
   echo "Invalid Length - $1" &&
   echo "$1" | checking_another_function_etc; then
    echo "some output" && exit 1
fi


可能的命令分隔可能会提供您期望的结果:


A possible separation of commands may provide what you expect:

if [ $# -ne 1 ]; then
    echo "Wrong number of arguments"
    exit 1
elif ! echo "$1" | lgt; then
    echo "Invalid length: $1"
    exit 1
elif echo "$1" | checking_another_function_etc; then
    echo "some output"
    exit 1
fi

&&运算符的LHS发出echo命令很少有用,因为它的退出状态始终为0.

It is rarely useful to make an echo command the LHS of the && operator, because its exit status is always 0.

这篇关于在if语句和函数中重击多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆