ssh to remote server and check if file exists

Hi everyone,

I am trying to figure out a way to ssh to remote server and check if file exists, and if it doesn't I want to leave the script with an exit status of 5.

I have the following that I am attempting to use, but it is not returning anything:

check()
{
ssh ${SOURCE_SERV} "ls -l ${SOURCE_FOLDER/${FILE}"
    if [ $0 -ne 0 ] ; then
	echo "\n${FILE} on ${SOURCE_FOLDER} does not exist"
    exit 1
fi
}

I know that the

works, as when I do this manually, the results are returned to the screen.

Does anyone have any suggestions or am I just going about this in completely the wrong way? We are running AIX 5.3 if that matters.

For the ksh shell this will return a 5 if file does not exist:

ssh user@host "( [[ -a "/path/to/file" ]] && return 0 ) || return 5"
print $?
5

If you want to capture the raw output then this might help,

x = `ssh  -f ${SOURCE_SERV} ls -l ${SOURCE_FOLDER/${FILE}`

x will contain the file name if it exists else it will be empty.

1 Like

Thanks everyone, that has helped me a lot!

You should be able to just call test on server via ssh

if ssh user@host "[ -f /path/to/file ]"
then
    echo "file exists"
else
    echo "no file (or ssh failure)"
fi