简体   繁体   中英

Setting a variable in a one-liner Bash script

Looking for a way to set a variable, in a bash one-liner, that is a script, such as:

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= ,

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.

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:

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'.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM