Tristan
Tristan

Reputation: 5

How to condition a bash script to send a warning

I have a script that is getting a file from sftp, modify it a little for path and access and then is used for import in mysql :

#!/bin/bash

sshpass -p password sftp -P 22001 ftp@server <<-'EOSSH1'
lcd path/where/to/be/grabbed
get *.csv
EOSSH1

#Moving and permission
mv original/path destination/path
chmod 777 file

#Insertion csv in mysql
mysql --login-path=user < cmds.txt (a file with commands to be executed in mysql)

Now, what I need is to put a condition like this : If the csv file is not in the sftp server, to send an email and not to run the script. If the file is there, everything to run fine.

Any idea how to do this?

BR Tristan

Upvotes: 0

Views: 360

Answers (1)

One.Punch.Leon
One.Punch.Leon

Reputation: 672

Run sftp in batch mode using -o BatchMode=yes. Provide the script from stdin, so -b -.

If get *.csv fails, then sftp will exit with non-zero status.

In your script you can check that exit status.

#!/bin/bash

sshpass -p password sftp -o BatchMode=yes -b - -P 22001 ftp@server <<-'EOSSH1'
lcd path/where/to/be/grabbed
get *.csv
EOSSH1

if [ "$?" -ne 0 ]; then
    echo "sftp failed. exiting..." >&2
    exit 1
fi

#Moving and permission
mv original/path destination/path
chmod 777 file

#Insertion csv in mysql
mysql --login-path=user < cmds.txt (a file with commands to be executed in mysql)

Manual page:

     -b batchfile
             Batch mode reads a series of commands from an input batchfile instead of stdin.  Since it lacks user interaction it should be used in conjunction with non-interactive authentication to obviate the need to enter a password at connection time (see sshd(8) and ssh-keygen(1) for details).

             A batchfile of ‘-’ may be used to indicate standard input.  sftp will abort if any of the following commands fail: get, put, reget, reput, rename, ln, rm, mkdir, chdir, ls, lchdir, chmod, chown, chgrp, lpwd, df, symlink, and lmkdir.

             Termination on error can be suppressed on a command by command basis by prefixing the command with a ‘-’ character (for example, -rm /tmp/blah*).  Echo of the command may be suppressed by prefixing the command with a ‘@’ character.  These two prefixes may be combined in any order, for example
             -@ls /bsd.


Alternative you can simply use scp:

sshpass -p password scp ftp@server:*.csv path/where/to/be/grabbed/ || exit 1

Upvotes: 1

Related Questions