[英]Is there a way of storing an query formula in Linux?
Linux can store functions, which can easily be called using the function
system. Linux可以存储函数,可以使用function
系统轻松地调用它们。 If I wish to write several if statements however that should use the same reasoning, can this be done? 如果我想编写多个if语句,但是应该使用相同的推理,可以这样做吗? For example: 例如:
if [ x == 1 ]
then
...
fi
If I need to use the x == 1
for umpteen formulas and vary all, can a block formula hold the equation so that I only need to make one modification instead of needing to modify all of them please? 如果我需要对多个公式使用x == 1
并全部改变,那么块公式可以容纳该公式,这样我只需要进行一次修改即可,而无需全部修改?
You can just wrap your logic in a function and use the function as the condition in the if
: 您可以将逻辑包装在一个函数中,并将该函数用作if
的条件:
my_check() {
[ "$x" -eq 1 ]
}
if my_check
then
echo yes
else
echo no
fi
This is taking advantage that the exit status of a shell function is the exit status of the last executed command. 这是利用Shell函数的退出状态是最后执行的命令的退出状态的优势。 So if "$x" equals one the return status of my_check
will be 0
(ie. success) and then you will enter the main branch. 因此,如果“ $ x”等于1,则my_check
的返回状态将为0
(即成功),然后您将进入主分支。 Otherwise exit status will be 1
(ie. failure) and then you will enter the alternate branch. 否则,退出状态将为1
(即失败),然后您将进入替代分支。
You could have multiple functions, one for each condition: 您可以具有多种功能,每种功能一种:
check_a() {
[ "$x" -eq 1 ]
}
check_b() {
[ "$x" -eq 2 ]
}
check_c() {
[ "$y" -eq 1 ]
}
if check_a && check_c
then
echo "a and c are true"
elif check_b && check_c
then
...
elif check_c
then
...
else
...
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.