Check if file exist

Hi,

I created following script to check if file exist:

#!/bin/bash
SrcDir=$1
SrcFileName=$2
SrcTimePeriod=$3
if [ -e $SrcDir/$SrcFileName_$SrcTimePeriod ];then
echo 1
else
echo 0
fi

I ran it like: /apps/Scripts/FileExist.sh /apps/Inbox file1 2nd_period_2010

Even file exist at that location, my above command is returning 0. If I hardcode values in script then it runs fine.

Am I missing something here?

Thanks!

$SrcFileName_

It considers that the whole variable. Instead try

${SrcFileName}_

That's why you should always put {} around variable names.

Heck, quote the whole thing for good measure too -- then it'll work on filenames with spaces.

if [ -e "${SrcDir}/${SrcFileName}_${SrcTimePeriod}" ];then
1 Like

Thanks for your reply.

I have one more question:

I want to use return code in another program. Right now I am using Echo to get 1 or 0. How can I use return code so that I can capture 1 or 0.

Thanks!

you have to use:
exit 0
else
exit 1...

In the next script you can intercept the exit code whit a special variable "$?"

example:

First script
...
exit 1
...

Second script
...
if [[ $? == 1 ]]; then
echo -e "First script has exited with '1'"
fi
...

Anyway, a script returns the return code of last command so your script can be much simplier, like:

#!/bin/bash
SrcDir=$1
SrcFileName=$2
SrcTimePeriod=$3
[ -e "${SrcDir}/${SrcFileName}_${SrcTimePeriod}" ]

Or without intermediate variables:

#!/bin/bash
[ -e "${1}/${2}_${3}" ]

Anyway, it's more just an expression than a script and you could code it directly in the calling script (if it's shell).
Note that the -e test refers to any file, for a regular file, preferably use -f