0

I have two "sayHello" shell scripts with only slightly changes on "if-else" test.

Here are the codes:

  • sayHello1
#!/bin/bash

read -e -p "What is your name? "

if [ -n $REPLY ]; then
    echo "Hello ${REPLY}!"
else
    echo "Hello ${USER}!"
fi
  • output for sayHello1 (I just pressed ENTER)
$ What is your name? 
$ Hello !

Here comes the strange thing. Why is $USER not shown in output?

If I change the test order as shown bellow:

  • sayHello2
#!/bin/bash

read -e -p "What is your name? "

if [ -z $REPLY ]; then
    echo "Hello ${USER}!"
else
    echo "Hello ${REPLY}!"
fi

  • output for sayHello2 (again, pressed ENTER)
$ What is your name? 
$ Hello rit!

it worked as expected.

With further test, I found that the command echo "${USER} can work expectedly anywhere outside "else-fi" block (within the script).

Why does this happen? How to explain it?

Cyrus
  • 84,225
  • 14
  • 89
  • 153

0 Answers0