Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot compare received user input via read

Tags:

bash

shell

I have the following shell script:

#!/bin/bash

if [ "`read -n 1`" == "c" ] ; then
    printf "\nfoo\n"
    exit 0
fi

printf "\nbar\n"
exit 0

However, regardless of the input, I always get bar as the output:

$ ./test.sh
c
bar
$ ./test.sh
d
bar

Why is this occuring and what do I need to change in the shell script?


1 Answers

You need to read it into a variable first, otherwise you're just comparing the output value of read (which is empty value).

Following should work:

#!/bin/bash

read -n 1 ch
if [ "$ch" == "c" ] ; then
    printf "\nfoo\n"
    exit 0
fi

printf "\nbar\n"
exit 0
like image 88
anubhava Avatar answered Feb 27 '26 01:02

anubhava