Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash if empty string

Some may have found out that in Ubuntu when you install or update via terminal

you get a question similar to

"do you with to install or remove package [Y/n]?"

when you press enter its like its the same as when you type "Y" or "y"

So i was wondering how to make that in bash This is what i have so far?

echo "question?[Y/n]"
read choose
if [ $choose ~= "Y" ] [ $choose ~= "y" ] [ $choose ~= "" ]
then 
#code
fi
like image 715
nkvnkv Avatar asked Dec 02 '25 06:12

nkvnkv


2 Answers

Classically (meaning it will work in POSIX-ish shells other than bash), you'd write:

echo "Question? [Y/n]"
read choose
if [ "$choose" = "Y" ] || [ "$choose" = "y" ] || [ -z "$choose" ]
then 
    # code
fi

The quotes ensure that the test operator see an argument even if $choose is an empty string.

The [[ operator seems to allow you to get away without quoting strings, but is not part of a POSIX shell. POSIX recognizes its existence by noting:

The following words may be recognized as reserved words on some implementations (when none of the characters are quoted), causing unspecified results:

[[    ]]    function    select

If you want the shell to leave the cursor on the same line as the prompt, you can use:

printf "Question? [Y/n] "

POSIX shells recognize the \c escape; bash does not:

echo "Question? [Y/n] \c"

(There may be a way to make bash handle that, but printf is probably more portable.)

like image 177
Jonathan Leffler Avatar answered Dec 04 '25 00:12

Jonathan Leffler


echo -n "Question? [Y/n]"
read choose 
shopt -s nocasematch
if [[ "${choose:=Y}" =~ Y ]]; then
     # they said yes
else
     # they said something else
fi

This approach has the possible advantage that it leaves $choose set to Y if you examine it later. If you prefer to be able to tell later whether they entered Y or just pressed enter, you can use ${choose:-Y} instead.

If you'd rather not set nocasematch, you can always check explicitly for both Y and y. Or, if you like the nocasematch solution but care about preserving the state of the flag, you can check and restore it:

shopt -q nocasematch
let not_set=$?
shopt -s nocasematch

...

if (( not_set )); then
   shopt -u nocasematch
fi
like image 45
Mark Reed Avatar answered Dec 03 '25 22:12

Mark Reed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!