[SOLVED] using getopts with flags to backup cronjobs
Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
logfile=mylog.log
log () {
local timestamp=$(date "+%D %H:%M:%S")
echo "$timestamp $1" >> $logfile
}
log "something is being logged"
log "Error: there was an error"
The command exit terminates your script so anything after is never executed.
1 is standard output (stdout) i.e. the echo command output goes to stdout.
2 is standard error (stderr) i.e. error messages are sent to stdout.
So 2>&1 means redirect both stdout and stderr to your logfile. I used the set -x mode to output the commands to help you debug your code. One way to turn the off the whole process is comment or remove the set command.
here is my latest code. now my question is, the script fails if a cronjob exists for a deleted user and exit. how can i check for deleted user and delete the orphan cronjob before it starts the rest of the backups?
Code:
#!/bin/bash -e
# This script by default is designed to backup all users crontab on host
# and must be run as root user.
# Use optional flags to set values other than default.
# default usage: script.sh
# optional usage: script.sh -m (backup||restore) -p (desire path) -u (user)
# see Help function for more detail on setting optionals.
cron_source='/var/spool/cron/crontabs' #default crontab location
bkuplocation='/systems/homes/cronjobs_bk' #default backup location
host="$(hostname -f)" #host FQDN
method='backup' #setting default method to backup
usercheck="$(cut -d: -f1 /etc/passwd)"
#Help function
function show_help {
echo "script must be run as root. "
echo "default usage : scriptname.sh -m (backup||restore) -p (location) -u (user)"
echo "Command line switches are -m , -p & -u "
echo "-m --Sets the value for option to backup or restore. Defaults to backup."
echo "-p --Sets the path to backup from and restore to. Defaults to $bkuplocation"
echo "-u --Sets the user's job for backup. Defaults to all"
echo "-h --Displays this help message. No further functions are performed."
exit 1
}
# Make sure only root can run this script
if [[ "$(id -u)" != "0" ]]; then # must run script as root
show_help
echo "user is not root. script must run as root"
exit 1
else
umask 0077
fi
#checking for $bkuplocation.
if [[ ! -d "${bkuplocation}" ]]; then
mkdir "${bkuplocation}" #create $bkuplocation folder if it does not exist
echo "${bkuplocation} does not exist. Created ${bkuplocation}"
fi
# Start getopts code
while getopts :m:p:u:h options; do
case "${options}" in
m)
method="${OPTARG}"
;;
p)
bkuplocation="${OPTARG}"
;;
u)
user="${OPTARG}"
;;
h)
show_help
;;
\?)
echo "Option ${OPTARG} not allowed."/n
show_help
;;
esac
done
#Error checking for default $bkuplocation. create if not exist.
if [[ ! -d "${bkuplocation}" ]]; then
echo "ERROR: Specified location ${location} does not exist."
echo "Please verify location or use default location by removing -p argument."
exit 1
fi
#Error checking for non-exist user.
if [[ ${method} = 'backup' && ! -z ${user} ]]; then
if [[ ! -f ${cron_source}/${user} ]]; then
echo "ERROR: no cronjob found for ${user} on ${host}."
exit 1
fi
fi
#Error checking for restore homeless user.
if [[ ${method} = 'restore' ]]; then
if [[ ! -z ${user} && ! -f "${bkuplocation}/${host}-${user}" ]]; then
echo "ERROR: no cron backup found for ${user} on ${host}."
exit 1
fi
fi
#Start getopts case code
case ${method} in
backup)
if [[ -z "${user}" ]]; then #default backup, no user input
cd "${cron_source}"
for users in *; do
crontab -l -u "${users}" > "${bkuplocation}/${host}-${users}"
done
elif [[ ! -z "${user}" ]]; then #backup with user input -u
crontab -l -u "${user}" > "${bkuplocation}/${host}-${user}"
else
echo "ERROR: Input option(s) not recognized."
show_help #show Help function if user input not recognized
fi
;;
restore)
if [[ -z "${user}" ]]; then #default restore for all users from default backup location
for users in "${bkuplocation}/${host}-*"; do #select $host files from default $bkuplocation
username="${users##*-}" #set username from selected files by removing $host-
crontab -u "${username}" "${users}" #crontab restore for all user
done
elif [[ ! -z "${user}" ]]; then #restore with user input -u
crontab -u "${user}" "${bkuplocation}/${host}-${user}"
else
echo "ERROR: Input option(s) not recognized."
show_help #show Help function if option(s) not recognized
fi
;;
esac
#verify completion of script run
if [[ "$?" -eq "0" ]]; then #use script exit code for verification
echo "successfully completed for ${host} ${user}"
else
echo "${method} failed for ${host} ${user}"
fi
exit 0
[edit] removed wrong notice, you do verify if crontab backup file exists if $user is set
- On both backup) and restore) actions, you test if $user is set and $user is not set (-z empty, null...), so these lines will never be executed (remove them)
Code:
else
echo "ERROR: Input option(s) not recognized."
show_help #show Help function if user input not recognized
fi
case ${method} in
backup)
if [[ -z "${user}" ]]; then #default backup, no user input
cd "${cron_source}"
for users in *; do
if [[ "{$user}" != $(cut -d: -f1 /etc/passwd | grep ${user}) ]]; then
echo "${user} is not an active user. Please consider remove the ${user} jobs"
else
crontab -l -u "${users}" > "${bkuplocation}/${host}-${users}"
fi
done
elif [[ ! -z "${user}" ]]; then #backup with user input -u
crontab -l -u "${user}" > "${bkuplocation}/${host}-${user}"
else
echo "ERROR: Input option(s) not recognized."
show_help #show Help function if user input not recognized
fi
;;
[edit] removed wrong notice, you do verify if crontab backup file exists if $user is set
- On both backup) and restore) actions, you test if $user is set and $user is not set (-z empty, null...), so these lines will never be executed (remove them)
Code:
else
echo "ERROR: Input option(s) not recognized."
show_help #show Help function if user input not recognized
fi
Yes, but when no user is passed, it will backup all users cronjob, which in this case the user is no longer exist and its just an orphan file that does not need to backup.
Thank you
Last edited by linuxnewbie0101; 07-06-2016 at 09:57 AM.
Yes, but when no user is passed, it will backup all users cronjob, which in this case the user is no longer exist and its just an orphan file that does not need to backup.
Thank you
I was talking about this block code (reduced)
Code:
if [[ -z "${user}" ]]; then #default backup, no user input
...
elif [[ ! -z "${user}" ]]; then #backup with user input -u
crontab -l -u "${user}" > "${bkuplocation}/${host}-${user}"
else
echo "ERROR: Input option(s) not recognized."
show_help #show Help function if user input not recognized
fi
You test if $user is not set, then elif test if $user is set...
what would be the alternative executed in else block?
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.