在单行 Bash 脚本中设置变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22003826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting a variable in a one-liner Bash script
提问by user3349369
Looking for a way to set a variable, in a bash one-liner, that is a script, such as:
寻找一种设置变量的方法,在 bash 单行中,即脚本,例如:
export class={read -p "What Is Your Profession?" a; case $a in "Theif") echo "Stealth" ; in "Cleric") echo "Heals?" ; "Monk") echo "Focus?" ; *) echo "invalid choice" a; esac}
Although I'm having issues running this command without setting it to a one-liner, I've tried it numerous ways and I have gotten no results. The above was just the most clearly laid out in my eyes. I've also tried VAR= ,
尽管我在不将其设置为单行命令的情况下运行此命令时遇到问题,但我已经尝试了多种方法,但没有得到任何结果。以上只是我眼中最清楚的布局。我也试过VAR= ,
The case itself gives me a
案例本身给了我一个
-jailshell: syntax error near unexpected token `('
whenever I run it with more than one case. I know this is probably all jumbled up.
每当我用多个案例运行它时。我知道这可能都是乱七八糟的。
回答by Jonathan Leffler
You need double-semicolons ;;
to separate the clauses of a case
statement, whether it is one line or many. You also have to be careful with { … }
because it is used for I/O redirection. Further, both {
and }
must be tokens at the start of a command; there must be a space (or newline) after {
and a semicolon (or ampersand, or newline) before }
. Even with that changed, the assignment would not execute the code in between the braces. For that, you could use command substitution:
无论是一行还是多行,您都需要双分号;;
来分隔case
语句的子句。您还必须小心,{ … }
因为它用于 I/O 重定向。此外,{
和}
必须是命令开头的标记;之后必须有一个空格(或换行符){
,之前必须有一个分号(或与号,或换行符)}
。即使更改了,赋值也不会执行大括号之间的代码。为此,您可以使用命令替换:
export class=$(read -p "What Is Your Profession?" a; case $a in "Theif") echo "Stealth" ;; "Cleric") echo "Heals?" ;; "Monk") echo "Focus?" ;; *) echo "invalid choice $a";; esac)
Finally, you've not run a spell-check on 'Thief'.
最后,您还没有对“小偷”进行拼写检查。
回答by anubhava
Here is one-liner you can use:
这是您可以使用的单线:
export class=`{ read -p "What Is Your Profession? " a; case $a in "Theif") echo "Stealth";; "Cleric") echo "Heals?";; "Monk") echo "Focus?";; *) echo "invalid choice" a;; esac; }`
OR better you can just put this inside a function:
或者更好的是你可以把它放在一个函数中:
function readclass() { read -p "What Is Your Profession? " a; case $a in "Theif") echo "Stealth";; "Cleric") echo "Heals?";; "Monk") echo "Focus?";; *) echo "invalid choice" a;; esac; }
Then use it:
然后使用它:
export class=$(readclass)