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" ]
    exit 0

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

  • 1
    Thumbs up on the "Rule of thumb" of always putting double-quotes around variables in tests! – Mark Stewart Feb 24 '16 at 23:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.