Bash backup checker [duplicate] - linux

This question already has answers here:
How do I set a variable to the output of a command in Bash?
(15 answers)
Closed 6 years ago.
I'm trying to compare dates from a file and the current day.
The script should run every day and if the dates do not compare it should give a warning.
I made a test file with a 2015 date, but it keeps saying its "equal" to the current date.
#!/bin/bash
today= date +"%m-%d-%y"
filedate= date +"%m-%d-%y" -r fileName.txt
if [ $today == $filedate ];
then
echo $today;
echo $filedate;
echo 'Backup OK';
else
echo $today;
echo $filedate;
echo 'Backup ERROR';
fi

find utility is your friend.
modified=$(find fileName.txt -mtime -1)
if [[ -n $modified ]]; then
echo OK
else
echo ERROR
fi
As a piece of advice you may have to read carefully what atime and ctime means to the system time.

You can assign the date output to the today and filedate variables using command substitution. And you'd better double quote your variables in your comparison test:
today=$(date +"%m-%d-%y")
filedate=$(date +"%m-%d-%y" -r fileName.txt)
echo $today
echo $filedate
if [ "$today" == "$filedate" ];
then
echo $today;
echo $filedate;
echo 'Backup OK';
else
echo $today;
echo $filedate;
echo 'Backup ERROR';
fi

This works for me.
today=$(date +"%m-%d-%y")
filedate=$(date +"%m-%d-%y" -r fileName.txt)
echo $today
echo $filedate
if [ "$today" == "$filedate" ];
then
echo $today;
echo $filedate;
echo 'Backup OK';
else
echo $today;
echo $filedate;
echo 'Backup ERROR';
fi

Related

Having difficulty checking a file for if input is repeated in a file using bash script

#!/bin/bash
#variables
option=$1
myfile=~/.bdrecord.txt;
#supported options
opts=("-a" "--test" "-app" "-c" "-v");
argc=("ram ram nov 12 pen | --test" "" "1s|1m|1h" "" "");
flag=0;
for o in ${opts[#]}
do
if [[ $o = ${option} ]];
then
flag=1;
break
fi
done
if [[ ${flag} -ne 1 ]];
then
echo -e "Program aborted!\nSupported commands are like"
for i in ${!opts[#]};
do
echo -e "$i.\t" $0 ${opts[$i]} ${argc[$i]}
done
fi
#defaults
name="Rambo"
nickname="Ram"
bmth=$(date +%h);
bday=$(date +%d);
gift="hat-type"
#new feature, handle --test option along with -a option
if [[ ${option} = "-a" ]];
then
while read -r name nickn month day gift
do
if [[ ${2} = ${name} ]];
then
isRepeated=1;
break;
fi
done
if [[ isRepeated == 1 ]]
then
echo "${name} is a repeated name. Try again."
exit 22;
fi
if [[ ${2} = "--test" ]];
then
#add some test data and exit.
for ((i=0;i<5; i++))
do
row="${name}-$i,${nickname},${bmth},$(($bday+$i)),${gift}-${i}";
echo ${row} >> ${myfile}
done
echo "Saved 5 samples in ${myfile}";
echo "...";
tail -n 5 ${myfile};
echo -e ".." $(cat ${myfile} | wc -l) "entries"
exit 0;
fi
#handle more or less than 5 inputs
if [[ $# -ne 6 ]];
then
echo "Expected 5 args (name nickname month day gift) with -a option."
exit 22;
fi
echo "option -a is received!"
#save last 5 inputs in the file
##collect last 5 inputs
name=$2
nickname=$3
bmth=$4
bday=$5
gift=$6
row="${name},${nickname},${bmth},${bday},${gift}";
echo ${row} >> ${myfile}
#display current date
echo "Today: $(date)";
#display "yeah.."
echo "Yeah ${nickname} has been added!"
#display count of records
echo "--------"
wc -l ${myfile}
fi
#handle -c option
#handle -v option
#new feature, handle -app option
if [[ ${option} = "--app" ]];
then
if [[ $# -ne 2 ]];
then
echo "Expected arg sleep time {1s, 2s, 3s..1m, 2m, 3m, ..1h, 2h, 3h..}";
exit 44;
fi
echo "Entered App Mode. Use kill command to kill it."
#find person whose birthday is today
thismonth=$(date +"%h")
ithismonth=$(date +"%m")
thisday=$(date +"%d")
bdlist=();
while IFS="," read -r name nickn month day gift
do
if [[ ("${month,,}" = "${thismonth,,}" \
||
"${month,,}" -eq "${ithismonth,,}") ]] \
&& [[ ${day} = ${thisday} ]]
then
#add to list
bdlist+=("Today is ${name}'s $day birthday! Selected gift is:${gift} ")
fi
done < ${myfile}
while :
do
#every hour send three messages notifying whose birthday is today.
sleep ${2};
for l in "${bdlist[#]}";
do
echo "$l" >> ~/.bdlog.txt;
done
let i++;
done
fi
The instructions of my assignment clearly state to: Modify the given script so that for the "-a" option, the script stores the arguments (name, nickname, birthday month, birthday day, gift) in the file ~/.bdrecord.txt only if the given input name does not exist in the record file ~/.bdrecord.txt
However, my code is erroring. The part that I added is the part where isRepeated is.

Trying to use this bash script to login to a remote ftp from ssh and delete files older than N days old

I am trying to use the following bash script to login to a remote ftp and delete files older than N days old. Script says it is working and does not give an error - but files are not being deleted. What am I missing? Or is there a better way to do this? Keep in mind this is only a remote FTP and not SSH so I can NOT use the mtime function is why I am trying to do this. Can anyone help?
The usage is all commands - here is what I am using via ssh to run the script
./ftprem.sh -s ftp.server.com -u myusername -p mypassword -f /directory -d 3
#!/bin/bash
PROGNAME=$(basename $0)
OUTFILE="/tmp/ftplist.$RANDOM.txt"
CMDFILE="/tmp/ftpcmd.$RANDOM.txt"
ndays=14
print_usage() {
echo ""
echo "$PROGNAME - Delete files older than N days from an FTP server"
echo ""
echo "Usage: $PROGNAME -s -u -p -f (-d)"
echo ""
echo " -s FTP Server name"
echo " -u User Name"
echo " -p Password"
echo " -f Folder"
echo " -d Number of Days (Default: $ndays)"
echo " -h Show this page"
echo ""
echo "Usage: $PROGNAME -h"
echo ""
exit
}
# Parse parameters
options=':hs:u:p:f:d:'
while getopts $options flag
do
case $flag in
s)
FTPSITE=$OPTARG
;;
u)
FTPUSER=$OPTARG
;;
p)
FTPPASS=$OPTARG
;;
f)
FTPDIR=$OPTARG
;;
d)
ndays=$OPTARG
;;
h)
print_usage
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
shift $(($OPTIND - 1))
if [[ -z "$FTPSITE" || -z "$FTPUSER" || -z "$FTPPASS" || -z "$FTPDIR" ]];
then
echo "ERROR: Missing parameters"
print_usage
fi
# work out our cutoff date
TDATE=`date --date="$ndays days ago" +%Y%m%d`
echo FTP Site: $FTPSITE
echo FTP User: $FTPUSER
echo FTP Password: $FTPPASS
echo FTP Folder: $FTPDIR
echo Removing files older than $TDATE
# get directory listing from remote source
ftp -i -n $FTPSITE <<EOMYF > /dev/null
user $FTPUSER $FTPPASS
binary
cd $FTPDIR
ls -l $OUTFILE
quit
EOMYF
if [ -f "$OUTFILE" ]
then
# Load the listing file into an array
lista=($(<$OUTFILE))
# Create the FTP command file to delete the files
echo "user $FTPUSER $FTPPASS" > $CMDFILE
echo "binary" >> $CMDFILE
echo "cd $FTPDIR" >> $CMDFILE
COUNT=0
# loop over our files
for ((FNO=0; FNO<${#lista[#]}; FNO+=9));do
# month (element 5), day (element 6) and filename (element 8)
FMM=${lista[`expr $FNO+5`]}
FDD=${lista[`expr $FNO+6`]}
FYY=${lista[`expr $FNO+7`]}
if [[ $FYY == *\:* ]]
then
FDATE=`date -d "$FMM $FDD" +'%Y%m%d'`
else
FDATE=`date -d "$FMM $FDD $FYY" +'%Y%m%d'`
fi
# echo $FDATE
# check the date stamp
if [[ $FDATE -lt $TDATE ]];
then
echo "Deleting ${lista[`expr $FNO+8`]}"
echo "delete ${lista[`expr $FNO+8`]}" >> $CMDFILE
COUNT=$[$COUNT + 1]
fi
done
echo "quit" >> $CMDFILE
if [[ $COUNT -gt 0 ]];
then
cat $CMDFILE | tr -d "\r" > $CMDFILE
ftp -i -n $FTPSITE < $CMDFILE > /dev/null
else
echo "Nothing to delete"
fi
rm -f $OUTFILE $CMDFILE
fi
If this helps your debugging...
In the# Parse parameter section of the script, the options variable your have just before the case block has value options=':hs:u:p:f:d:' instead of options=':h:s:u:p:f:d:'
I thought i should point that out.

Trying to implement CASE in my shell script

I'm trying to add options to my little safe delete script. For example, I can do ./sdell -s 100 and it will delete files with size above 100 kbs. Anyway, I'm having problems with my safe guard function.
#!/bin/bash
#Purpose = Safe delete
#Created on 20-03-2018
#Version 0.8
#jesus,i'm dumb
#START
##Constants##
dir="/home/cunha/LIXO"
#check to see if the imputs are a files#
for input in "$#"; do
if ! [ -e "$input" ]; then
echo "Input is NOT a file!"
exit 1
fi
done
###main###
case $1 in
-r) echo "test option -r"
;;
*) if [[ -f "$dir/$fwe.tar.bz2" ]]; then
echo "File already exists."
if [[ "$file" -nt "$2" ]]; then
echo "Removing older file." && rm "$dir"/"$fwe.tar.bz2" && tar -czPf "$fwe.tar.bz2" "$(pwd)" && mv "$fwe.tar.bz2" "$d$
fi
else
echo "Ziping it and moving." && tar -czPf "$fwe.tar.bz2" "$(pwd)" && mv "$fwe.tar.bz2" "$dir"
fi
done
;;
esac
The problem is when I call ./sdell -r file1.txt, it says that the input is not a file.
Here is the script without the case, 100% working before having options.
#!/bin/bash
#Purpose = Safe delete
#Created on 20-03-2018
#Version .7
#START
##Constants##
dir="/home/cunha/LIXO"
#check to see if the imputs are a files#
for input in "$#"; do
if ! [ -e "$input" ]; then
echo "Input is NOT a file!"
exit 0
fi
done
###main###
##Cycle FOR so the script accepts multiple file inputs##
for file in "$#"; do
fwe="${file%.*}"
#IF the input file already exist in LIXO#
if [[ -f "$dir/$fwe.tar.bz2" ]]; then
echo "File already exists."
#IF the input file is newer than the file thats already in LIXO#
if [[ "$file" -nt "$2" ]]; then
echo "Removing older file." && rm "$dir"/"$fwe.tar.bz2" && tar -czPf "$fwe.tar.bz2" "$(pwd)" && mv "$fwe.tar.bz2" "$d$
fi
else
echo "Ziping it and moving." && tar -czPf "$fwe.tar.bz2" "$(pwd)" && mv "$fwe.tar.bz2" "$dir"
fi
done
The message you are seeing is unrelated to the case..esac, construct, it is printed by this section:
for input in "$#"; do
if ! [ -e "$input" ]; then
echo "Input is NOT a file!"
exit 1
fi
done
which expands all command-line parameters ($#), including the "-r", and exits the script because "-r" is not a file. The case..esac is never reached. You can run your script with
bash -x file.sh -r test
so that you can see exactly which lines are being executed.
The snippet below probably does what you want, processing all arguments sequentially:
#!/bin/bash
while [ ! -z $1 ]; do
case $1 in
-r) echo "option R"
;;
-f) echo "option F"
;;
*) if [ -f $1 ]; then echo "$1 is a file." ; fi
;;
esac
shift
done
Consider checking if -r has been passed before trying other options and use shift if it was:
#!/usr/bin/env sh
dir="/home/cunha/LIXO"
case $1 in
-r) echo "test option -r"
shift
;;
esac
#check to see if the imputs are a files#
for input in "$#"; do
echo current input: "$input"
if ! [ -e "$input" ]; then
echo "Input $input is NOT a file!"
exit 1
fi
done
if [[ -f "$dir/$fwe.tar.bz2" ]]; then
echo "File already exists."
if [[ "$file" -nt "$2" ]]; then
echo "Removing older file..."
# add stuff
fi
else
echo "Ziping it and moving."
# add stuff
fi

file check 3 times and exit shell script

I want to check for file in directory if there then push it to ssh server checing server connection if file not there then try 3 times with each 1min interval and in between if it comes ( on 2nd attend for example) then try again to connect ssh and push. else check for 3 attempts and exit
Please check my below code it is halting after 1st attempt ( during 2nd attempt I am making file available)
#!/bin/sh
echo "OK, start pushing the Userdetails to COUPA now..."
cd /usr/App/ss/outbound/usrdtl/
n=0
until [ $n -ge 3 ] || [ ! -f /usr/App/ss/outbound/usrdtl/USERS_APPROVERS_*.csv ]
do
if [ -f /usr/App/ss/outbound/usrdtl/USERS_APPROVERS_*.csv ] ;
then
pushFiles()
else
n=$[$n+1]
sleep 60
echo " trying " $n "times "
fi
done
pushFiles()
{
echo "File present Now try SSH connection"
while [ $? -eq 0 ];
do
echo $(date);
scpg3 -v /usr/App/ss/outbound/usrdtl/USERS_APPROVERS_*.csv <sshHost>:/Incoming/Users/
if [ $? -eq 0 ]; then
echo "Successfull"
echo $(date);
echo "Successfull" >> /usr/App/ss/UserApproverDetails.log
exit 1;
else
echo $(date);
echo "Failed" >> /usr/App/ss/UserApproverDetails.log
echo "trying again to push file.."
scpg3 -v /usr/App/sg/outbound/usrdtl/USERS_APPROVERS_*.csv <ssh Host>:/Incoming/Users/
echo $(date);
exit 1;
fi
done
}
I've tried to simplify this code for you. I hope it helps:
#!/bin/bash
outdir="/usr/App/ss/outbound/usrdtl"
logfile="/usr/App/ss/UserApproverDetails.log"
file_prefix="USERS_APPROVERS_"
function push_files() {
echo "File present now try SSH connection"
local attempts=1
local retries=2
date
while [[ ${attempts} -lt ${retries} ]]; do
if scp ${outdir}/${file_prefix}*.csv <sshHost>:/Incoming/Users/ ; then
echo "Successful" | tee -a ${logfile}
date
exit 0
else
echo "Failed" >> ${logfile}
fi
attempts=$((attempts+1))
do
echo "scp failed twice" | tee -a ${logfile}
exit 2
}
echo "OK, start pushing the Userdetails to COUPA now..."
cd ${outdir}
attempts=1
retries=3
while [[ ${attempts} -lt ${retries} ]]; do
echo "looking for files...attempt ${attempts}"
if test -n "$(shopt -s nullglob; echo ${outdir}/${file_prefix}*.csv)"; then
push_files()
fi
attempts=$((attempts+1))
sleep 60
done
echo "Files were never found" | tee -a ${logfile}
exit 1
Look at this code and tell me how it's not doing what you're trying to do. The most complicated part here is the nullglob stuff, which is a handy trick to see if any file in a glob matches
Also, I generally used bashisms.

ShellScript Issue Linux [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Task 1:
If the Time is AM, print "It is Morning". If it is PM, print "It is not morning".
Task 2:
Given 2 arguments passed to the script.
Validate that 2 arguments have been submitted. If three arguments have not been provided, print "Must Supply 2 Arguments" and exit the script
Argument 1: Should be a directory (needs validated). If this does not exist, print "Directory: directory, does not exist" and exit the script
Argument 2: Should be a file (needs validated). If this does not exist, print "File: filename, does not exist" and exit the script.
If all arguments are valid, print "Given valid: filename and directory"
This is what I have so far
echo "James DuBois: 555555 - Task 1"
TIME=$(date "+%H")
if [ $TIME -lt 12 ]; then
echo "morning"
else
echo "not morning"
fi
echo "Task 2"
[ -d "$1" ] || exit
[ -d "$2" ] || exit
[ $# == 2 ] || exit
echo "arg1: $1"
echo "arg2: $2"
James, BASH is a wonderful, flexible shell. It has its warts, but if you need to do anything having to do with Linux system administration, etc.., you can do it in bash. Your tasks are to familiarize you with using conditional expressions (tests). There are tests for just about anything you need. That's why I pointed you to the CONDITIONAL EXPRESSIONS part of man bash.
Your second task requires the input of a filename so you can test it. I presume it is intended to be passed as an argument to your script (called positional parameters). Here is one way to approach the test. Note: I have interchanged output routines echo and printf intentionally for your benefit (printf being a bit more robust). Take a look at the following and let me know what questions you have:
#!/bin/bash
# My first script
#
# echo & printf are used at random below -- intentionally
#
[ -z $1 ] && { # validate at least 1 argument given on command line
printf "error: insufficient input. usage: %s filename\n" "${0##*/}"
exit 1
}
printf "\nJames DuBois: 5555555\n\n Task 1\n\n"
TIME=$(date "+%H")
## test for time of date: morning/not morning
if [ $TIME -lt 12 ]; then
printf " morning - time for coffee\n"
else
echo " not morning - time for scotch"
fi
echo -e "\n Task 2\n"
printf "Testing whether '%s' is a valid file.\n\n" "$1"
## test for file using compound commands
[ -f "$1" ] && echo -e " file found: '$1'\n" || printf " file not found: '%s'\n\n" "$1"
echo -e "Second test whether '$1' is a valid file.\n"
## test for file using if; then; else; fi
if [ -f "$1" ]; then
printf " file found: '%s'\n\n" "$1"
else
echo -e " file not found: '$1'\n"
fi
exit 0
Use/Output
$ bash ~/scr/tmp/stack/morningfile.sh
error: insufficient input. usage: morningfile.sh filename
$ bash ~/scr/tmp/stack/morningfile.sh mtrx_simple_dyn.c
James DuBois: 5555555
Task 1
not morning - time for scotch
Task 2
Testing whether 'mtrx_simple_dyn.c' is a valid file.
file found: 'mtrx_simple_dyn.c'
Second test whether 'mtrx_simple_dyn.c' is a valid file.
file found: 'mtrx_simple_dyn.c'
$ bash ~/scr/tmp/stack/morningfile.sh dog.c
James DuBois: 5555555
Task 1
not morning - time for scotch
Task 2
Testing whether 'dog.c' is a valid file.
file not found: 'dog.c'
Second test whether 'dog.c' is a valid file.
file not found: 'dog.c'
This will have some additional advantages while doing the same thing in task 2:
echo "Task 2"
[[ -d $1 && ! -L $1 && -f $2 && ! -L $2 ]] || exit
printf "%s\n" "arg1: $1" "arg2: $2"
It checks for symbolic links with the -L option.
[[ ]] has some advantages over [ ] like dealing with white spaces without the need for quoting variables.
If you want to print messages while checking for directory and file:
[[ ! -d $1 || -L $1 ]] && echo "Directory doesn't exist" && exit
[[ ! -f $2 || -L $2 ]] && echo "File doesn't exist" && exit
printf "%s\n" "arg1: $1" "arg2: $2"

Resources