Answer the question
In order to leave comments, you need to log in
How does cron work?
I'm trying to get a script to run using cron.
There is a user on the server, let's call vpsuser
There is a backup.sh script in his home folder
If you run it $ sudo ~/backup.sh >> ~/backup.log
, then everything is OK, and like this
* * * * * /home/vpsuser/backup.sh >> /home/vpsuser/backup.log
/home/vpsuser/backup.sh
/home/vpsuser/backup_sources
/home/vpsuser/createbare.sh
/home/vpsuser/.bash_aliases
/home/vpsuser/.bashrc
/home/vpsuser/.cdargs
/home/vpsuser/.gitconfig
/home/vpsuser/.profile
/home/vpsuser/.ssh
/home/vpsuser/.config
/home/vpsuser/crontab.backup
/home/vpsuser/letsencrypt
/home/vpsuser/mongodb
/etc/letsencrypt
/etc/ssh
/etc/nginx
/var/log/nginx
/var/www
#!/bin/bash
set -e
shopt -s dotglob
# Цвет текста сообщения об ошибке
red=$(tput setf 4)
# Цвет текста сообщения об успешном выполнении
green=$(tput setf 2)
# Стандартный цвет текста консоли
reset=$(tput sgr0)
# Параметры, которые помещают уведомление о выполнении операции вправо
toend=$(tput hpa $(tput cols))$(tput cub 6)
TIMESTAMP=$(date +'%F_%R:%S' -d "-24 hour")
HOME=/home/vpsuser
NOW=$(date +%d-%m-%Y)
PROCESS_NAME=$(basename $0)
SOURCE_FILE="${HOME}/backup_sources"
BACKUP_FILE="${HOME}/backup_${NOW}.tar.gz"
CRONTAB_FILE="${HOME}/crontab.backup"
PID_FILE="$$.lock"
MONGO_DIR="${HOME}/mongodb"
PID_DIR=/var/run/${PROCESS_NAME}
TAR="$(which tar)"
if [ -f ${PID_DIR}/${PID_FILE} ]; then
echo "${PROCESS_NAME} уже запущен!"
exit 1
fi
function print_status {
if [ $? -eq 0 ]; then
echo -n "${green}${toend}[OK]"
else
echo -n "${red}${toend}[ERROR]"
fi
echo -n "${reset}"
echo
}
function create_lock_file() {
mkdir -p ${PID_DIR} && touch ${PID_DIR}/${PID_FILE}
}
function remove_lock_file() {
[ -d ${PID_DIR} ] && rm -rf ${PID_DIR}
}
function create_mongo_dump() {
mkdir -p ${MONGO_DIR}
mongodump --gzip --out=${MONGO_DIR} &> /dev/null
}
function remove_mongo_dump() {
if [ -d "${MONGO_DIR}" ]; then
rm -rf ${MONGO_DIR}
fi
}
function create_crontab_dump() {
crontab -l > ${CRONTAB_FILE}
}
function remove_crontab_dump() {
if [ -f "${CRONTAB_FILE}" ]; then
rm -f ${CRONTAB_FILE}
fi
}
function backup() {
echo -n "Сохраняем бэкап в файл ${BACKUP_FILE}"
${TAR} -czvf "${BACKUP_FILE}" -N"${TIMESTAMP}" -T"${SOURCE_FILE}" &> /dev/null
print_status;
}
create_lock_file;
create_mongo_dump;
create_crontab_dump;
backup;
remove_crontab_dump;
remove_mongo_dump;
remove_lock_file;
Answer the question
In order to leave comments, you need to log in
In backup.sh, you need to specify all files (both programs and data) with the full path to them or in crontab specify all the necessary search paths in PATH
maybe
* * * * * sh /home/vpsuser/backup.sh >> /home/vpsuser/backup.log
?
* * * * * - and this is how to read?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question