A
A
Andrew Floatrx2017-01-20 19:05:31
bash
Andrew Floatrx, 2017-01-20 19:05:31

How to simplify a Bash construct without using if then else!?

Depending on the Y or N key pressed, the Variable variable takes the value TRUE (y) or FALSE (n)...
Is it possible to describe this construction in a simpler way:

read -r -n1 -p "Ask some question. y/n " key
if [${key^^}=="Y"]; then
    variable=true
else
    variable=false
fi

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Saboteur, 2017-01-20
@saboteur_kiev

You can remove else

read -r -n1 -p "Ask some question. y/n " key
variable=false
if [ ${key^^} == "Y" ]; then
    variable=true
fi

You can use && and ||
read -r -n1 -p "Ask some question. y/n:" key
[ ${key^^} = 'Y' ] && variable=true || variable=false

3
3vi1_0n3, 2017-01-21
@3vi1_0n3

Can be even easier

read -r -n1 -p "Ask some question. y/n:"
[ ${REPLY^^} == 'Y' ]
variable=$?

Well, then check the value of variable. If 0, then everything is fine (true), if not 0, then the equality is not true (false)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question