Return value error

Hi All,

I am new to shell sciprting and i have written a small script to get the filename if it exists. I need to capture the file name using the script and i also need the exit status. The problem i am facing is,though my file does not exists, iam getting the exit status as '0'. Please help me out.

My scripts is as follows;

#!/usr/bin/ksh
folder='/stagep03/cca/data/'
cd $folder
wild='*'
dated=`date +%m%d%y`
filename=`ls -l $1$dated$wild | tail -1 |grep ^-|awk '{print $9}'`
echo $filename
echo $?

The output iam getting is;

$ sh test.ksh PROCESS1.CAIRP.SSZCKST.A_R.
ls: 0653-341 The file PROCESS1.CAIRP.SSZCKST.A_R.030112* does not exist.
0

Thanks in advance.

Remove the line "echo $filename". If do not want to remove, instead of "echo $0", check for $filename is not null.

Guru.

Thanks for the reply,

I removed $filename and run the script..but still iam facing the same problem. If the output is as "ls: 0653-341 The file PROCESS1.CAIRP.SSZCKST.A_R.030112* does not exist." why the exit status is 0?

exit status 0 means the previous command return is true, which means this was executed correctly.
$? gives the return of the previously executed command.

you are executing

echo $filename echo $?

This mean echo command ran successfully which is the last command before "echo $?"

your error is coming while executing "ls -l" but with echo.

I have removed echo $filename from my scrip. Now my "echo $?" is next to "filename=`ls -l $1$dated$wild | tail -1 |grep ^-|awk '{print $9}'`"

the exit status should not be '0' if the file does not exist. right?.

but it is '0'.

You are having couple of sub shells which causing it to be $?=0.

Try this and check

#!/usr/bin/ksh
folder='/stagep03/cca/data/'
cd $folder
wild='*'
dated=`date +%m%d%y`
ls -l $1$dated$wild
echo $?

Please note, you are invoking the script with old bourne shell. This simply ignores the shebang of the script (ksh)

To cope with the pipes (subshell), ksh93 having pipefail option.

$ ls nofile | more
ls: nofile: No such file or directory
$ echo $?
0
$ set -o pipefail
$ ls nofile | more
ls: nofile: No such file or directory
$ echo $?
2 
$

One possible rearrangement of your script to let Shell use filename globbing.
Note that the "ls -1" below is "ls hyphen-one" not "ls hyphen-ell".

#!/usr/bin/ksh
folder='/stagep03/cca/data/'
cd "${folder}"
dated="`date +%m%d%y`"
prefix="${1}${dated}"

test -f "${prefix}"* ; REPLY=$?
echo "REPLY=${REPLY}"

if [ ${REPLY} -eq 0 ]
then
        ls -1d "${prefix}"*
fi

It is declared as single quotes ( which is correct and important I guess) and used without quotes which will expand.

filename=`ls -l $1$dated$wild | tail -1 |grep ^-|awk '{print $9}'`

This ultimately resolves to

filename=`ls -l PROCESS1.CAIRP.SSZCKST.A_R.030112* | tail -1 |grep ^-|awk '{print $9}'`

Or I misunderstood you?

The return code where you have it is the result of assigning the command substitution to the variable "filename", which succeeded.