1

I have a bash script, which, at one point asks the user for confirmation. I do this by reading a single character, which is then transformed to lower case and checked if it is 'y'. If not, the script exits.

Now, if I simply press enter on the input read, I get error: unary operator expected. How can I prevent this issue or catch the error?

Code snippet:

echo -ne "Confirm [y/n]: "
read -n1 uc

if [ ${uc,,} != "y" ]
then
    exit 0
fi
Anthon
  • 79,293
boolean.is.null
  • 2,553
  • 7
  • 19
  • 24

1 Answers1

5

This statement should work properly:

if [ "${uc,,}" != "y" ]

Explanation: When uc is empty your test is expanded by the shell as follows:

if [  != "y" ]

while with the quotes it is

if [ "" != "y" ]

Rule of thumb: Always use quotes around shell variables that contain strings when expanding them; they may contain spaces or be empty, which when unquoted often confuses the command they're passed to (too many or missing parameters).

Murphy
  • 2,649