Problem when passing argument to a shell script

Hi all,

I'm new to Shell scripting. In my shell script for Bourne shell, the script accepts a date parameter which is optional. If the value is supplied, the supplied value should be assigned to a variable. If not, the current date will be assigned to the variable. My script is like this.

#! /bin/sh

if [ ! -z $1 ]
then
dateval=`date`
elif [ $dateval -gt date ];then
echo "Supplied date is greater than current date"
else
 dateval=$1
fi
echo $dateval

When i run the script, it says

./shellpgm30.sh: test: argument expected

Any help would be appreciated.

Thanks,
Sumesh

Please use code tags when you are posting some code. I put your code within the tags.

In your script, the value of $dateval is not initialized in elif [ $dateval -gt date ];then. and hence you cant test it against date.

And how can you compare dates with the -gt construct ?

And what is date in that same line. Did you mean $date ?

Try this.

#! /bin/sh

if [ $# -eq 0 ] ; then
  dateval=`date`
else
  dateval=$1
fi
echo $dateval

You are getting this error since $1 does not contain any value.Use double square brackets to avoid this problem.

if [[ -z $1 ]]

Thanks Vino. The problem is solved.
Anbu,

if [[ -z $1 ]]

does not work.

It tells

./shellpgm30.sh: [[: not found

Is it the snippet for ksh.

Appreciate your help

[[ works in both ksh and bash

Anbu,
Thanks for the reply.

I'm using sh. The sample code is given below.

#! /bin/sh
if [[ -z $1 ]]
then
echo "Does not contain any value"
else
 echo "Contains value"
fi

I executed the script as

 ./shellpgm32.sh

I get error as

./shellpgm32.sh: [[: not found

Can u please explain?

Thanks,
Sumesh

I think [[ is not available in bourne shell.

Thanks Anbu.

[[ ]] construct is available in bash. Standard shell lacks the construct, and I think the problem may be that sumesh is assuming that /bin/sh is a symlink to bash (which is the case on some systems).

If you use ksh, you can avoid all the test logic. All you need to do is:

dateval=${1:-$(date)}