英文:
Check if variables are not empty strings in bash with a reverse case switch statement
问题
以下是您要翻译的内容:
我有一些变量,对于每个变量,我需要执行以下操作:
如果变量是""
,则不执行任何操作
如果变量不是""
,则执行echo "text $var"
每个变量将需要发送不同的文本。
我想要使用case
语句来完成这个任务。
通常它们的工作方式如下:
case $var in
a)
echo "a"
;;
*)
;;
esac
然而,我希望它可以像这样工作:
case !"" in
$var1)
echo "var1"
;;&
$var2)
echo "var2"
;;&
esac
如果表达式是""
或类似于"1"
,那么它可以与变量成功比较。但它不接受!""
或我能想到的其他“不是""”的变化,因此它不起作用。
我可以使用多个if
语句、一个函数或一个for
循环来遍历这些变量来完成这个任务。但我看不到只使用case
来完成的方法。
英文:
I have a number of variables and for each one I need to do the following:
If the variable is ""
, do nothing
If the variable isn't ""
, then echo "text $var"
.
Each variable will need to send different piece of text.
The way I would like to do this would be with case
statements.
Normally they work like this:
case $var in
a)
echo "a"
;;
*)
;;
esac
However, I would like it to work like this:
case !"" in
$var1)
echo "var1"
;;&
$var2)
echo "var2"
;;&
esac
If the expression is ""
or something like "1"
then it can be compared with the variables successfully. But it doesn't accept !""
or other variations of not ""
that I can think of so it doesn't work.
I could do this with several if
statements, a function or a for
loop iterating over the variables. But I can't see a way to do it with only case
.
答案1
得分: 1
无法使用 not
来排除 case
中的特定值。相反,应匹配那些不应该执行任何操作的情况,并在匹配时不执行任何操作。
在这个示例中,""
和 "#"
将不执行任何操作。我使用了 ;&
来让 ""
继续匹配到 "#"
,只是为了能够记录它对这两者都不执行任何操作。
#!/bin/bash
var=$1
var1=a
var2=b
case $var in
"$var1")
echo "text var1"
;;
"$var2")
echo "text var2"
;;
"")
;&
"#")
echo "doing nothing"
;;
*)
echo "doing the default thing"
;;
esac
英文:
You can't exclude certain values from the case
by using not
. Instead, match on those that shouldn't result in any action too, and, do nothing if you get a match.
In this example, ""
and "#"
will result in doing nothing. I've used ;&
to let ""
fallthrough to "#"
just to be able to log that it's doing nothing for both of them.
#!/bin/bash
var=$1
var1=a
var2=b
case $var in
"$var1")
echo "text var1"
;;
"$var2")
echo "text var2"
;;
"")
;&
"#")
echo "doing nothing"
;;
*)
echo "doing the default thing"
;;
esac
答案2
得分: 1
以下是翻译好的部分:
- You can do this with an alternate value expansion:
${var1:+x}
will expand to "x" if the variable is set to a non-empty value, and "" otherwise. So something like this should work. - But I'd consider this an ugly hack, and prefer a function or something similar as a cleaner solution.
英文:
You can do this with an alternate value expansion: ${var1:+x}
will expand to "x" if the variable is set to a non-empty value, and "" otherwise. So something like this should work.
case "x" in
${var1:+x}) echo "$var1" ;;&
${var2:+x}) echo "$var2" ;;&
${var3:+x}) echo "$var3" ;;&
esac
But I'd consider this an ugly hack, and prefer a function or something similar as a cleaner solution.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论