Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a variable in a one-liner Bash script

Tags:

bash

case

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.

like image 912
user3349369 Avatar asked Dec 15 '22 01:12

user3349369


2 Answers

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

like image 104
Jonathan Leffler Avatar answered Jan 03 '23 10:01

Jonathan Leffler


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)
like image 22
anubhava Avatar answered Jan 03 '23 09:01

anubhava