shell script backing up the source directory to backup directory - bash

#!/bin/bash
BACKUP=backup_date
SOURCE=Arithmetic_Operators
echo "Taking backup from ${SOURCE} directory to backup directory ${BACKUP} .."
# Checking the source directory ${SOURCE} exists or not ! if not exists die
# Script is unsuccessful with exit status # 1
[ ! -d $SOURCE ] && echo "source directory $SOURCE not found"
exit 1
# Checking the backup directory ${BACKUP} exists or not ! if not exists die
# Script is unsuccessful with exit status # 2
[ ! -d $BACKUP ] && echo "backup directory $BACKUP not found"
exit 2
# Let Start the backing up
tar cvf $SOURCE $BACKUP 2> /wrong/logs.txt
if [ $? -ne 0 ]
then
# die with unsuccessful shell script termination exit status # 3
echo "An error occurred while making a source directory backup, see /wrong/logs.txt file".
exit 3
fi
This is my script to backing up the source directory(Arithmetic_Operators) to destination directory (backup_date), while running the script my script was ending with message
Taking backup from Arithmetic_Operators directory to backup directory backup_date ..
source directory Arithmetic_Operators not found
where i did mistake why this script is not running could you please help me on this ?

These lines mean the script exits unconditionally:
[ ! -d $SOURCE ] && echo "source directory $SOURCE not found"
exit 1
You probably meant:
if [ ! -d $SOURCE ]
then
echo "source directory $SOURCE not found" >&2
exit 1
fi
Or maybe:
[ ! -d $SOURCE ] && { echo "source directory $SOURCE not found" >&2; exit 1; }
Note that error messages should be sent to standard error, not standard output. It wouldn't be a bad idea to include the name of the script ($0) in the messages; it helps identify which script generated/detected the problem.
You have a similar problem after checking the $BACKUP directory.
Also, as a general rule, enclose variable references in double quotes:
[ ! -d "$SOURCE" ] && { echo "source directory $SOURCE not found" >&2; exit 1; }
(The second reference is already inside double quotes, of course.)

Related

Bash script to copy file from one directory to other directory

I want to automatically create a directory without entering data from the keyboard.
Where should I place my *.war* file for backup then I have to copy this file to another directory here I should remove existing file and copy this new file in * *.
You can use the rsync command with the argument --delete, example:
folder a: 2019-05-21.war
folder b: 2019-05-15.war
when you run rsync it will erase whatever is different in the destination folder.
script examples:
#!/bin/bash
origin_dir="/opt/a"
dest_dir="/opt/b"
log=$(date +"/tmp/%F-bkp.log" -u)
rsync -avz --delete $a/ $b/ >> $log 2>&1
#if you want to keep backup for less than a week, delete the older files in origin
[ -d "$a/" ] && find $a/ -type f -name '*.war' -mtime +6 -exec rm {} \;
One a little more verbose example showing you typical things that you can do easily in a shell script.
#!/bin/bash
trap f_cleanup 2 # clean-up when getting signal
PRG=`basename $0` # get the name of this script without path
DEST=$HOME/dest # XXX customize this: the target directory
#
# F U N C T I O N S
#
function f_usage()
{
echo "$PRG - copy a file to destination directory ($DEST)"
echo "Usage: $PRG filename"
exit 1
}
function f_cleanup()
{
echo ">>> Caught Signal, cleaning up.."
rm -f $DEST/$1
exit 1
}
#
# M A I N
#
case $# in
1)
FILE=$1 # command line argument is the file to be copied
;;
*)
echo "$PRG: wrong number of arguments ($#), expected 1"
f_usage
;;
esac
while getopts "h?" opt; do
case "$opt" in
h|\?)
f_usage
;;
esac
done
if [ ! -f $FILE ]; then
echo "$PRG: error: file not found ($FILE)" && exit 1
fi
if [ ! -d $DEST ]; then
echo "$PRG: warning: dest dir ($DEST) does not exist, trying to create it.."
mkdir -p $DEST && echo "$PRG: dest dir ($DEST) successfully created"
if [ $? -ne 0 ]; then
echo "$PRG: error: dest dir ($DEST) could not be created"
exit 1
fi
fi
cp -p $FILE $DEST
RET=$? # return status of copy command
case $RET in
0) echo "$PRG: copying $FILE to $DEST was successful"
rm $FILE
;;
*) echo "$PRG: copying $FILE to $DEST was not successful"
exit 1
;;
esac

I am having a hard time why the if statements don't work in ShellScript

I am having a hard wondering why is it that when i type the most random names they are accepted as a directory then. and when an if statement checks if its a readable file it says yes for all i type in. the goal here is search for a directory check if it is a directory. then search the directory for a file then in that file search for word in it using forloops. the while loop is to ask 3 times for the file name. It a little bit rough I just need an explanation for the if statements not working
#!/bin/sh
DIR='/home/collin2/'
x=1
echo "Please enter directory"
read directory
for directory in "$DIR";
do
if [ -d "$directory" ];
then echo "This is a directory Please enter the file name"
read filename
while [ $x -le 3 ]; do
for filename in "$directory";
do
if [ -r "$filename" ]
then echo "The filename is readable"
echo "Please Enter a word "
read word
grep "$word" "$filename"
exit 1
fi
done
echo "Doesn't exist please try again"
read filename
x=`expr $x + 1`
done
#exit 1
fi
done
echo "not a directory"
exit 0
Your for commands are wrong:
Wheb you write for directory in "$DIR";, it will set the value of the variable directory to "$DIR". You wanted to check, that you could find directory in "$DIR" , that can be done without a for command:
cd "$DIR" || { echo "Can not go to $DIR"; exit 1; }
test -d "${directory}" || { echo "Wrong directory ${directory}"; exit 1; }
# or
test -d "$DIR/${directory}" || { echo "Can not go to $DIR"; exit 1; }
The same problem with the other for-loop.
The test if [ -r "$filename" ] should be done after cd "$DIR/${directory}" or include the complete path.

How can I create an updating directory log in unix?

The goal of this script is to create a log file if it does not exist, or update the existing log file if it does exist of the directory that the user inputs when the program is run. My problem is that I cannot find a way to compare the log file with the current state of the directory while still being able to update the log file properly, and display each file that is being added to the screen. This is the code I am using so far:
userinput=$1
if [ ! -d "$userinput" ];
then
echo "Usage: dirlog.sh directory_name" 1>&2
exit 0
else
if [ ! -f "$userinput.log" ];
then
ls -l > $userinput.log
echo ".logfile created for $userinput"
elif [ -f "$userinput.log" ];
then
if [ ];
then
echo "$file missing from directory $userinput"
else #file not missing
echo "no files missing from directory $userinput"
fi
#Update this no matter what
ls -l > $userinput.log
echo "logfile updated for directory $userinput"
fi
fi

Getting an EOF error, I've searched for sytax errors cannot see

Getting these two errors when running a simple script to just make a repo for a user.
This is a bash script
ERROR:
./createMyRepo.sh: line 48: unexpected EOF while looking for matching `"'
./createMyRepo.sh: line 52: syntax error: unexpected end of file
#!/bin/bash
# This script is used to automate the repo
if [ -z `$1` ]
then
echo "No user was input, please input a user and try again"
exit
else
cd /home/$1
if [ $? -eq 0 ]
then
echo "Successfully changed directory to user's home"
else
echo "Failed to cd directory, trying to create directory now."
mkdir /home/$1
if [ $? -eq 0 ]
then
echo "Successfully created the directory location
else
echo "Failed to create directory, exiting."
exit
fi
fi
mkdir project.git
if [ $? -eq 0 ]
then
echo "Succesfully created project.git directory"
else
echo "Failed to create project.git directory attempting to see if the directory already exists"
cd project.git
if [ $? -eq 0 ]
then
echo "Successfully changed to this directory"
else
echo "This directory cannot be created and does not exist. exiting..."
exit
fi
fi
cd project.git
echo "creating git repo"
git --bare init
if [ $? -eq 0 ]
then
echo "DONE Created repo"
else
echo "FAIL repo did not create"
fi
fi
oops ... look like a typo error
echo "Successfully created the directory location
should be in this form:
echo "Successfully created the directory location"
The line echo "Successfully created the directory location is missing a " at the end, so that Bash is completely confused about where your strings are and aren't.
(Hat-tip to Stack Exchange's syntax highlighting, which makes the problem obvious!)
Also, I suggest you adopt a better indentation scheme; your current scheme makes it very difficult to trace nested ifs and so on.

Extending bash script to receive more parameters?

I have the following bash script, which is called trash.sh. In my script I request one parameter for from the user, simply a file name. And move the file to the Trash folder which is located in the user's home directory. If the directory doesn't exist, it simply creates one and then moves the file there. On the other hand, if the file doesn't exist, it informs the user.
#!/bin/bash
FILE=$1
FOLDER="$HOME/Trash"
ARGS=1
if [ $# -ne $ARGS ]
then
echo "Error: You are missing an argument!"
echo "Usage: ./trash.sh <file_name>"
else
if [ -s $FILE ]
then
if [ -d $FOLDER ]
then
mv -v $FILE $FOLDER
else
mkdir $FOLDER
mv -v $FILE $FOLDER
fi
else
echo "The file you have entered does not exist!"
fi
fi
Now, I want to extend my script in the followign ways, but I don't know how, because I am not that much experienced with bash scripting. First of all, I want to let the user enter more than one parameters, simply more then one file name, and move all the files in the Trash folder. If one or more of the files don't exist, it will inform the user which file or files don't exist. Simply, I want my script to recieve as many parameters as the user wants.
For example, if the user calls the script like this:
./trash.sh file1 file2 file3
and let's say that file2 doesn't exist I want the output to be.
file1 -> /home/user/Trash/file1
file3 -> /home/user/Trash/file3
file2 doesn't exist!
And lastly, I also want it to accept a parameter like this:
./trash *.txt
Simply, which will move all the files that end with .txt extension. If someone could help me achieve those things/extend my script, I would be glad.
[ $# = 0 ] && { echo "Usage: $0 file [...]" >&2; exit 1; }
FOLDER="$HOME/Trash"
mkdir -p "$FOLDER" || exit 1
for file in "$#"
do
if [ -s "$file ]
then mv -v "$file" "$FOLDER"
else echo "$0: $file does not exist" >&2
fi
done
You can detect zero arguments and issue a usage message before the loop. Using "$#" is crucial to working with filenames containing blanks, etc; ditto with using "$file" to reference the files. Using mkdir -p does not fail if the target directory already exists; it does fail if the directory can't be created or if a file with the given name exists (instead of a directory). Note that the error messages both contain $0; note that the 'file not found' message specifies the file name.
As discussed in the comments, you can simplify this in two steps:
[ $# = 0 ] && { echo "Usage: $0 file [...]" >&2; exit 1; }
FOLDER="$HOME/Trash"
mkdir -p "$FOLDER" || exit 1
for file in "$#"
do mv -v "$file" "$FOLDER"
done
and then:
[ $# = 0 ] && { echo "Usage: $0 file [...]" >&2; exit 1; }
FOLDER="$HOME/Trash"
mkdir -p "$FOLDER" || exit 1
mv -v "$#" "$FOLDER"
Note that if you delete the makefiles in three directories, only one of them will be in the Trash.

Resources