How to tell in the script that if the scp failed, try wget - linux

I have this script :
cd /tmp/
scp user#8.8.4.1:/onboot/OTA.sh /tmp -i /usr/script/id 2> /dev/null
if
chmod 775 /tmp/OTA.sh
/tmp/OTA.sh &
sleep 30
rm -rf /tmp/OTA.sh
fi
I want to tell in the script that if the scp failed, try wget

man scp
EXIT STATUS
The scp utility exits 0 on success, and >0 if an error occurs.
The exit status can be accessed using the variable $? in bash.

$? contains exit code of last called command. You can simply check if its non-zero:
scp user#8.8.4.1:/onboot/OTA.sh /tmp -i /usr/script/id 2> /dev/null
if [[ $? -ne 0 ]]
then
#wget here
fi

Related

Hot to get exit code of wget ftp

I need to get exit code of ftp execution. My command line is:
wget -N ftp://server:pass#server/path/
Using:
if [ $? -ne 0 ]; then
will check wget execution.
not tested:
wget [wget options] 2>&1 | grep -i "failed\|error"

BASH: redirect for log dillema / duplicate redirection for each loop iteration

I've got a redirect dilemma that I can't get past in a bash backup script I'm developing in CentOS 6.4. I want to redirect all output to two separate files: one tmp and one permanent. The script loops through an external source list and I'd like for the tmp log files to be specific to the source, so that I can send an email if that specific source had errors containing that log (and conversely remove the tmp if the backup completes without error).
I'm using exec to tee my output:
exec > >(tee -a ${templog} /var/log/rob/rob.log) 2>&1
This works if I place at the top of the script, but here the variable isn't defined yet, so I can't do source-specific logs.
If I place this within the while loop, it grabs the variable, but writes a copy of each line determined by the total iterations of the loop; for the example below, I have four sources it iterates through, so I get output for each source in quadruplicate:
-S-07/11/14 09:15:35 ROB-Source Process for cc2-gamma has started-S-
-S-07/11/14 09:15:35 ROB-Source Process for cc2-gamma has started-S-
-S-07/11/14 09:15:35 ROB-Source Process for cc2-gamma has started-S-
-S-07/11/14 09:15:35 ROB-Source Process for cc2-gamma has started-S-
Share cc2-gamma is not Mounted. Try 1 of 5 to mount...
Share cc2-gamma is not Mounted. Try 1 of 5 to mount...
Share cc2-gamma is not Mounted. Try 1 of 5 to mount...
Share cc2-gamma is not Mounted. Try 1 of 5 to mount...
Is there a different way to tee the output within the loop to prevent this (without touching each line of course)? Or is there something rotten in my loops that I'm not seeing? Here's the whole script. Please excuse the mess and style.. I'm clearly not finished. I didn't include the config.conf and backup source file as they don't affect the output. Let me know if needed. Thanks.
#!/bin/bash
#V.2014.0723 - Radation Oncology Backup script
#declarations
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/rob
source /rob/conf/config.conf
while read smbdir 'smbpath' exclfile drive foldername; do
#loop declarations
mountedfile=/rob/${smbdir}.MOUNTED
runningfile=/rob/${smbdir}.RUNNING
lastrunfile=/rob/${smbdir}_${foldername}.LASTRUN
templog=/rob/${smbdir}_${foldername}.TMPLOG
errorfile=/rob/${smbdir}_${foldername}.HAD_ERRORS
backupfile=/rob/${baname:0:3}_rtbackup.sql.bz2 # for the -l seccton below -- sql backup of backup.sql
#exec > >(tee -a ${templog} /var/log/rob/rob.log) 2>&1
### SOURCE BACKUP ##############################################################################################
if [ "$1" == "-s" ]
then
exec > >(tee -a /var/log/rob/rob.log ${templog}) 2>&1
#Write Source STDOUT and STDERR to both permanent and temporary log file. Must be in loop to use variables.
#exec > >(tee -a ${templog} /var/log/rob/rob.log) 2>&1
#exec > >(tee -a /var/log/rob.log ${templog}) 2>
if [ "${sources_active}" == "1" ]
then
echo "-S-$(date "+%m/%d/%y %T") ROB-Source Process for $smbdir has started-S-"
# unmount all cifs shares, due to duplicate mounts, write file to prevent concurrentcy
umount -a -t cifs > /dev/null
# The following will test to see if the souce is mounted, and if not, mount it.
for i in {1..5}
do
if mountpoint -q /mnt/${smbdir}/${drive}/${foldername}
then
echo "Share ${smbdir} is Mounted."
touch $mountedfile
break
else
sleep 2
echo "Share ${smbdir} is not Mounted. Try $i of 5 to mount..."
mkdir -p /mnt/${smbdir}/${drive}/${foldername} > /dev/null
mount -t cifs ${smbpath} -o ro,username=<USER>,password=<PW>,workgroup=<DOMAIN> /mnt/${smbdir}/${drive}/${foldername}
fi
done
# Test to see if above was successful, and if rob is not already running, run the backup.
if [[ -f ${mountedfile}&& ! -f ${runningfile} ]]
then
src="/mnt/${smbdir}/$drive"
dst="/backup/rob/"
touch ${runningfile}
/root/bin/rtbackup -m /mnt -p ${src}/${foldername} -b ${dst} -x #${exclfile}
if [ "$?" -ne "0" ]; then
#Errors Running RTBackup
rm -f ${runningfile} > /dev/null 2>&1
rm -f ${mountedfile}> /dev/null 2>&1
echo "$(date "+%m/%d/%y %T") Source Process for ${smbdir} had errors running:-SSS"
echo "$errors" >&2
touch ${errorfile}
exit 1
else
echo "What the hell is this doing?"
fi
#NO Errors Running RTBACKUP
rm -f ${templog}
rm -f ${runningfile} > /dev/null 2>&1
rm -f ${mountedfile} > /dev/null 2>&1
echo "$(date "+%m/%d/%y %T") Source Process for ${smbdir} did not have any errors"
else
#backup will *NOT* run, cleaning up and logging
rm -f ${mountedfile} > /dev/null 2>&1
echo "$(date "+%m/%d/%y %T") ${smbdir} could not be mounted, or is already in progress. Backup could not complete."
touch ${errorfile}
tail /var/log/rob/robso.log | mail -s "ROBSO Failed to run for ${smbdir} on ${baname}" ${email}
fi
echo "-F-$(date "+%m/%d/%y %T") ROB-Source Process for ${smbdir} has finished-F-"
#break
elif [[ "${sources_active}" == "0" ]]
then
echo "***$(date "+%m/%d/%y %T") ROB-Source Process for ${smbdir} did not run because the job is not set as active***"
#break
fi
done < /rob/conf/${baname}.conf
if [ $? -eq 10 ]; then exit 0; fi
You can use curly braces to redirect a set of commands; as it says in the bash manual about command grouping, "When commands are grouped, redirections may be applied to the entire command list". It behaves more-or-less like an anonymous function.
{
command1
command2
} > >(tee -a ${templog} /var/log/rob/rob.log) 2>&1
You can do the same with a named function, too, if you're so inclined, but I don't know offhand what environment would be used to expand the redirections. (If you do, please edit this answer!)
# Untested. This MIGHT work.
your_log_command() {
command1
command2
} > >(tee -a $1 /var/log/rob/rob.log) 2>&1
your_log_command $templog
your_log_command $something_else

Check if rsync command ran successful

The following bash-script is doing a rsync of a folder every hour:
#!/bin/bash
rsync -r -z -c /home/pi/queue root#server.mine.com:/home/foobar
rm -rf rm /home/pi/queue/*
echo "Done"
But I found out that my Pi disconnected from the internet, so the rsync failed. So it did the following command, deleting the folder.
How to determine if a rsync-command was successful, if it was, then it may remove the folder.
Usually, any Unix command shall return 0 if it ran successfully, and non-0 in other cases.
Look at man rsync for exit codes that may be relevant to your situation, but I'd do that this way :
#!/bin/bash
rsync -r -z -c /home/pi/queue root#server.mine.com:/home/foobar && rm -rf rm /home/pi/queue/* && echo "Done"
Which will rm and echo done only if everything went fine.
Other way to do it would be by using $? variable which is always the return code of the previous command :
#!/bin/bash
rsync -r -z -c /home/pi/queue root#server.mine.com:/home/foobar
if [ "$?" -eq "0" ]
then
rm -rf rm /home/pi/queue/*
echo "Done"
else
echo "Error while running rsync"
fi
see man rsync, section EXIT VALUES
Old question but I am surprised nobody has given the simple answer:
Use the --remove-source-files rsync option.
I think it is exactly what you need.
From the man page:
--remove-source-files sender removes synchronized files (non-dir)
Only files that rsync has fully successfully transferred are removed.
When unfamiliar with rsync it is easy to be confused about the --delete options and the --remove-source-files option. The --delete options remove files on the destination side. More info here:
https://superuser.com/questions/156664/what-are-the-differences-between-the-rsync-delete-options
you need to check the exit value of rsync
#!/bin/bash
rsync -r -z -c /home/pi/queue root#server.mine.com:/home/foobar
if [[ $? -gt 0 ]]
then
# take failure action here
else
rm -rf rm /home/pi/queue/*
echo "Done"
fi
Set of result codes here:
http://linux.die.net/man/1/rsync

Restarting apache without being superuser

Is there any possibility to perform graceful restart and check apache config syntax without being root or having root privileges?
I have already tried to set suid bit to the script which performs restart. Here is the script itself:
#!/bin/bash
FILENAME=$1
DATE=`date +%Y%m%d`
DIRECTORY='bckp/'
if [ ! -d "$DIRECTORY" ]; then
echo "Backup directory doesn't exist. Creating one."
mkdir $DIRECTORY
fi
if [ -z "$FILENAME" -a ! -f "$FILENAME" ]; then
FILENAME="webdav.conf"
echo "No file specified. Backing up webdav.conf"
fi
REV=0
BACKUP="$FILENAME.$DATE.$REV"
while [ -f $BACKUP ]; do
let REV+=1
BACKUP="$DIRECTORY$FILENAME.$DATE.$REV"
done
cp $FILENAME $BACKUP
echo $OUTPUT
OUTPUT=$(apache2ctl configtest 2>&1)
if [ "$OUTPUT" == "Syntax OK" ]; then
echo "Syntax OK"
echo "Performing restart"
apachectl -k graceful 2>&1
fi
exit $?
here is the ls -l for this file:
-rwsrwxr-x 1 root user 645 2012-04-26 18:05 graceful-restart
When i try to run this script i get the following output:
No file specified. Backing up webdav.conf
ulimit: 88: error setting limit (Operation not permitted) Syntax OK
I'm interested if it is possible to perform what i've described.
Linux will not honor the suid bit on a shell script. Read this for more information.
A common solution for this is the sudo command. With an entry like this in /etc/sudoers:
yourname ALL = NOPASSWD:/path/to/graceful-restart
You could run:
sudo /path/to/graceful-restart
And this would run with root privileges without prompting you for a password. See the sudoers man page for more information on the syntax of the sudoers file.

Error trapping scp exit code not working

I have
# Transfer today's CMS backup to a remote backup server
scp -P 55 -r $localdumpdirectory/dirdump-cms-`date +%Y%m%d`.tar.gz root#someserver:/$remotedumpdirectory/ >/dev/null 2>&1
status=${$}
if [[ ${status} != 0 ]]
then
echo "Failed to secure copy directory, with code: ${status}"
exit 1
fi;
Everything is working except that even though the SCP succeeds, I get:
Failed to secure copy directory, with code: 27348
Ideas?
Exit code is $?, not $$. $$ is process ID.
status=${$}
should be
status=$? # or ${?} if you really insist.
If this is bash, see the section "Special Parameters" in the documentation.
Do you want
status=$?
That will give you the status of the last command.
status=$$
This is giving you the last PID
http://tldp.org/LDP/abs/html/internalvariables.html#PROCCID
BTW, you can shorten what you have to:
if scp -P 55 -r $localdumpdirectory/dirdump-cms-`date +%Y%m%d`.tar.gz root#someserver:/$remotedumpdirectory/ >/dev/null 2>&1
then
echo "Failed to secure copy directory, with code: ${status}"
exit 1
fi

Resources