Thursday, March 6, 2008

Amazing bash scripting

Here is a simple bash script

1 #!/bin/bash
2
3 var=''
4
5 if [ -z ${var} ]; then
6 echo "ZERO"
7 else
8 echo "NOT ZERO"
9 fi
10
11 if [ -n ${var} ]; then
12 echo "NOT ZERO"
13 else
14 echo "ZERO"
15 fi
16

How do you think? What will be on your terminal after you execute it?
Suppose

ZERO
ZERO

?

Actually - no :)

ZERO
NOT ZERO

Why? For the moment I do know the solution for the problem, but I really can't explain why that is going on. Here is a solution:

1 #!/bin/bash
2
3 var=''
4
5 if [ -z "${var}" ]; then #we do make sure it's string
6 echo "ZERO"
7 else
8 echo "NOT ZERO"
9 fi
10
11 if [ -n "${var}" ]; then # ... and here
12 echo "NOT ZERO"
13 else
14 echo "ZERO"
15 fi
16

Amazing!?

Here is the answer: http://bash-hackers.org/wiki/doku.php?id=commands:classictest

No comments: