我有一个var,它应该包含一个或其他字符串值或退出程序。
第一个似乎对我有用:
[ !"$JOB_FILE" == "all_jobs.pl" ] || [ !"$JOB_FILE" == "incomplete.out" ] && { echo -e "\n Only all_jobs.pl or incomplete.out are valid job files\n"; exit 127 ; }
然而,第二个不是:
[ "$JOB_FILE" != "all_jobs.pl" ] || [ "$JOB_FILE" != "incomplete.out" ] && { echo -e "\n Only all_jobs.pl or incomplete.out are valid job files\n"; exit 127 ; }
两个不相等的定义之间有什么区别。
答案 0 :(得分:1)
这些是正确的形式:
[ ! "$JOB_FILE" == "all_jobs.pl" ] && [ ! "$JOB_FILE" == "incomplete.out" ] && {
echo -e "\n Only all_jobs.pl or incomplete.out are valid job files\n"
exit 127
}
[ "$JOB_FILE" != "all_jobs.pl" ] && [ "$JOB_FILE" != "incomplete.out" ] && {
echo -e "\n Only all_jobs.pl or incomplete.out are valid job files\n"
exit 127
}
在Bash中,这更好:
[[ $JOB_FILE != "all_jobs.pl" && $JOB_FILE != "incomplete.out" ]] && {
echo -e "\n Only all_jobs.pl or incomplete.out are valid job files\n"
exit 127
}
或者这个:
shopt -s extglob ## Not necessary on Bash 4.1 or newer.
[[ $JOB_FILE != @(all_jobs.pl|incomplete.out) ]] && {
echo -e "\n Only all_jobs.pl or incomplete.out are valid job files\n"
exit 127
}
使用regex
也是可能的,但它更难逃脱。
答案 1 :(得分:0)
好像你有一个逻辑错误。如果两个语句都为真,但您使用||
,则需要执行回显。你真的想要使用&&
。
if [[ "$JOB_FILE" != "all_jobs.pl" && "$JOB_FILE" != "incomplete.out" ]]; then
echo -e "\n Only all_jobs.pl or incomplete.out are valid job files\n"
exit 127
fi
答案 2 :(得分:0)
一种方法是检查文件名是否是预期的文件名,并使用逻辑OR来链条:
[ "$JOB_FILE" = "all_jobs.pl" ] || [ "$JOB_FILE" = "incomplete.out" ] || { echo -e "\n Only all_jobs.pl or incomplete.out are valid job files\n"; exit 127 ; }
答案 3 :(得分:0)
逻辑是相反的。
您想要检查JOB_FILE
是“A”还是“B”。在其他情况下,请输出错误消息。
JOB_FILE status
A ok
B ok
rest error
因此
A B (A or B) !(A or B) !A or !B !A and !B
1 0 1 0 0 or 1 => 1 0 and 1 => 0
0 1 1 0 1 or 0 => 1 1 and 0 => 0
0 0 0 1 1 or 1 => 1 1 and 1 => 1
--------------------------------------------------------------
always true just true if not A and not B
1=True
,0=False
。
在这种逻辑味道之后,你需要的是:
[ ! "$JOB_FILE" == "all_jobs.pl" ] && [ ! "$JOB_FILE" == "incomplete.out" ] && { echo ... }
^^