Operating System - Linux
1753510 Members
5163 Online
108795 Solutions
New Discussion юеВ

Re: Checking the null entry in Shell Scripting

 
SOLVED
Go to solution
CA1490051
Frequent Advisor

Checking the null entry in Shell Scripting

Hi,

I am trying to write a script for different options the user enters.

the small snippet is as follows


read Choice

if [ $Choice -eq 1 ]
then
...............
else
................
fi

Now the problem is i also want to check for the null i.e, if the user enters nothing in the console and presses enter.

How can i check this null in the script .

thanks in advance
Vikram
7 REPLIES 7
Oviwan
Honored Contributor
Solution

Re: Checking the null entry in Shell Scripting

Hey

if [[ $# -eq 0 ]]
then
echo no arguments
fi

Regards
James R. Ferguson
Acclaimed Contributor

Re: Checking the null entry in Shell Scripting

Hi:

read REPLY
case ${REPLY} in
0 ) echo "..."
;;
1 ) echo "..."
;;
"" ) echo "please enter something!"
;;
* ) echo "error!"
;;
esac

Regards!

...JRF...
CA1490051
Frequent Advisor

Re: Checking the null entry in Shell Scripting

Hi,

But i think you are talking about command line arguments.

the problem i am facing is with scanning the values using "read"


i have written like this

read Choice
if [ $Choice -eq 1 ] || [ -z $Choice ]
...........

fi

if i try to run the script and give enter in the console i.e null string it says
"Specify a parameter with this command"

But i think i have checked for the null also .

I am not understanding what should i do to satisfy the above if condition.
Bernd Reize
Trusted Contributor

Re: Checking the null entry in Shell Scripting

If you don't use parameters but want your script to be interactive you could do it the following way:

read input

if [ -z "$input" ]; then
# zero/empty input
fi

CA1490051
Frequent Advisor

Re: Checking the null entry in Shell Scripting

thank you very much to all for helping me to find solution
Matti_Kurkela
Honored Contributor

Re: Checking the null entry in Shell Scripting

Always use double quotes when expanding variables that contain user input!

The user might type something strange, like ";cat /etc/passwd;".

This allows the user to by-pass the menu system and run commands directly. If the script is run as root (using a "setuid root" wrapper program or sudo), this gives the user a way to run any commands with unlimited access.

Even if this script is not security-critical, it's good to make a habit of always using quotes. It makes your scripts more robust and this way you're less likely to make dangerous mistakes elsewhere.

MK
MK
Dennis Handly
Acclaimed Contributor

Re: Checking the null entry in Shell Scripting

You can also check for null strings like:
$ if [ "$Choice" = "" ]; then