unix shell script creating backup.sh - unix

How to write a shell script named "backup.sh" which accepts one parameter, which would be a filename/directory.
Create a backup copy of that with the .bak appended to its name.Show message on success.
If the file/directory does not exist, show a proper message.
i did up to this point.please help me to figure this out
#!/bin/sh
#create_backup.sh
And add a .bak
bak="${backup.sh}.bak"
if [ "$#" -eq 0 ]
then
exit 1;
echo "File Succesfully backuped"
fi
cp ${1} "${1}.back"
echo "File is not found "
exit 0

#!/bin/bash -e
directory=$1
cp -r $directory $directory.bak
echo "Success"
obvious caveats with pathing/error codes/etc

Related

How to tell script to look only into a specific folder

I'm trying to make a recycle bin for UNIX, so I have two scripts. 1 to delete the file and move it to the bin, the other script to restore the file back to its original location.
my restore script only works if the person gives the path to the deleted file.
ex: sh restore ~/trashbin/filename
How do I hardcode into my script so that I don't need to give the path to the deleted file it should already know to look in the trashbin for the file. My restore script works only when someone calls in the path to the file.
#!/bin/bash
rlink=$(readlink -e "$1")
rname=$(basename "$rlink")
function restoreFile() {
rlink=$(readlink -e "$1")
rname=$(basename "$rlink")
rorgpath=$(grep "$rname" ~/.restore.info | cut -d":" -f2)
rdirect=$(dirname "$rorgpath")
#echo $orgpath
if [ ! -d "$rdirect" ]
then
mkdir -p $rdirect
#echo $var
mv $rlink $rorgpath
else
mv $rlink $rorgpath
fi
}
if [ -z "$1" ]
then
echo "Error no filename provided."
exit 1
elif [ ! -f "$1" ]
then
echo "Error file does not exist."
exit 1
elif [ -f "$rorgpath" ]
then
echo "File already exists in original path."
read -p "Would you like to overwrite it? (y/n)" ovr
if [[ $ovr = y || $ovr = Y || $ovr = yes ]]
then
echo "Restoring File and overwriting."
restoreFile $1
grep -v "$rname" ~/.restore.info > ~/.restorebackup.info
mv ~/.restorebackup.info ~/.restore.info
fi
else
echo "Restoring file into original path."
restoreFile $1
grep -v "$rname" ~/.restore.info > ~/.restorebackup.info
mv ~/.restorebackup.info ~/.restore.info
fi
When you "remove" the file from the file-system to your trash-bin, move it so that its path is remembered. Example: removing file /home/user/file.txt should mean moving this file to ~/.trash/home/user/file.txt. That way, you'll be able to restore files to the original location, and you'll have auto-complete work, since you can do: sh restore ~/.trash/<TAB><TAB>

Unix - If file arguments already have

###Takes filenames as arguments and makes those executable
#create file variable
file=$*
chmod 755 $file
if [ $? -eq 0 ] ; then
echo permission change suceeded
else
echo permission change failed
exit 0
fi
This is my current code - I'm wanting to add an extra echo which will be "already got executable permission" - how would i add a check onto this to check that if it has executable permission or not
if [ -x "$file" ]; then
echo "already got executable permission"
else
....
fi
Check
help test
perm="$(stat -c "%a" $file)"
if [$perm -eq 755]; then
...
else
...
fi

UNIX - Moving a deleted file back to it's original directory

All I want to do is move a file from my created recycle bin to it's own original path.
My code is as follows:
#!/bin/bash
restore ()
{
base=`basename $restore_file | cut -d"_" -f1`
echo "Your file $base has been restored"
mv deleted/$restore_file /$HOME/$base
}
restore_file=$1
if [ $# -eq 0 ]
then
echo "You have not entered a file"
elif [ -e deleted/$restore_file ]
then
restore
grep -v $(basename $restore_file) $HOME/.restore.info >> $HOME/.restore.inf o.tmp
cp $HOME/.restore.info.tmp $HOME/.restore.info
rm $HOME/.restore.info.tmp
else
echo "Your file "$restore_file" does not exist"
fi
I'm sure the error is in on line 7, just not sure how to rewrite. Any ideas?
Do you need to put a full path in before deleted?
You don't need the slash before $HOME, but that shouldn't be a problem.

Need to add logic in Unix script convert from Windows to Unix format

I am having one script need to add logic that if some one add file from winscp and do not convert into plain text while transfer. so some time we get some special character (^m) in some value, i wanted to remove them
Here is my code.
cd $HOME_DIR
if [ $SHELL_STEP = 'step2' ]; then
if [ -s $DATA_DIR/$DATA_FILE.txt ]; then echo "The data file is present." cat -v new_reguest.txt $ awk '{ sub("\r$", ""); print }' new_request.txt > new_request.txt echo "Data file $DATA_FILE.txt found in $DATA_DIR directory." >> $LOG_FILE echo "" >> $LOG_FILE STATUS='good' else echo "The data file has not arrived yet." fi
if [ $STATUS = 'bad' ]; then
echo "The data file not found."
echo "The data file not found." >> $LOG_FILE
echo "" >> $LOG_FILE
SHELL_STEP='step5'
else
SHELL_STEP='step3'
fi
fi
I tried to using awk command, but it's not looking good.
please assist.
Most implementations will provide tools like dos2unix or d2u to remove carriage returns from the end of lines. You can use something like:
dos2unix new_request.txt >new_request_2.txt
mv new_request_2.txt new_request.txt
If you don't have the dos2unix command, you can do the same thing with sed:
sed -i 's/\r$//' new_request.txt
The -i is for in-place editing. If your version of sed doesn't have that, you'll have to resort to the same temporary file trick used in the dos2unix code above.

Find out if a command exists on POSIX system

I want to be able to tell if a command exists on any POSIX system from a shell script.
On Linux, I can do the following:
if which <command>; then
...snip...
fi
However, Solaris and MacOS which do not give an exit failure code when the command does not exist, they just print an error message to STDOUT.
Also, I recently discovered that the which command itself is not POSIX (see http://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html)
Any ideas?
command -v is a POSIX specified command that does what which does.
It is defined to to return >0 when the command is not found or an error occurs.
You could read the stdout/stderr of "which" into a variable or an array (using backticks) rather than checking for an exit code.
If the system does not have a "which" or "where" command, you could also grab the contents of the $PATH variable, then loop over all the directories and search for the given executable. That's essentially what which does (although it might use some caching/optimization of $PATH results).
One which utility is available as shell script in the Git repository of debianutils package of Debian Linux. The script seems to be POSIX compatible and you could use it, if you take into account copyright and license. Note that there have been some controversy whether or not and how the which utility should be deprecated; (at time of writing) current version in Git shows deprecation message whereas an earlier version added later removed -s option to enable silent operation.
command -v as such is problematic as it may output a shell function name, an alias definition, a keyword, a builtin or a non-executable file path. On the other hand some path(s) output by which would not be executed by shell if you run the respective argument as such or as an argument for command. As an alternative for using the which script, a POSIX shell function using command -v could be something like
#!/bin/sh
# Argument $1 should be the basename of the command to be searched for.
# Outputs the absolute path of the command with that name found first in
# a directory listed in PATH environment variable, if the name is not
# shadowed by a special built-in utility, a regular built-in utility not
# associated with a PATH search, or a shell reserved word; otherwise
# outputs nothing and returns 1. If this function prints something for
# an argument, it is the path of the same executable as what 'command'
# would execute for the same argument.
executable() {
if cmd=$(unset -f -- "$1"; command -v -- "$1") \
&& [ -z "${cmd##/*}" ] && [ -x "$cmd" ]; then
printf '%s\n' "$cmd"
else
return 1
fi
}
Disclaimer: Note that the script using command -v above does not find an executable whose name equals a name of a special built-in utility, a regular built-in utility not associated with a PATH search, or a shell reserved word. It might not find an executable either in case if there is non-executable file and executable file available in PATH search.
A function_command_exists for checking if a command exists:
#!/bin/sh
set -eu
function_command_exists() {
local command="$1"
local IFS=":" # paths are delimited with a colon in $PATH
# iterate over dir paths having executables
for search_dir in $PATH
do
# seek only in dir (excluding subdirs) for a file with an exact (case sensitive) name
found_path="$(find "$search_dir" -maxdepth 1 -name "$command" -type f 2>/dev/null)"
# (positive) if a path to a command was found and it was executable
test -n "$found_path" && \
test -x "$found_path" && \
return 0
done
# (negative) if a path to an executable of a command was not found
return 1
}
# example usage
echo "example 1";
command="ls"
if function_command_exists "$command"; then
echo "Command: "\'$command\'" exists"
else
echo "Command: "\'$command\'" does not exist"
fi
command="notpresent"
if function_command_exists "$command"; then
echo "Command: "\'$command\'" exists"
else
echo "Command: "\'$command\'" does not exist"
fi
echo "example 2";
command="ls"
function_command_exists "$command" && echo "Command: "\'$command\'" exists"
command="notpresent"
function_command_exists "$command" && echo "Command: "\'$command\'" does not exist"
echo "End of the script"
output:
example 1
Command: 'ls' exists
Command: 'notpresent' does not exist
example 2
Command: 'ls' exists
End of the script
Note that even the set -eu that turns -e option for the script was used the script was executed to the last line "End of the script"
There is no Command: 'notpresent' does not exist in the example 2 because of the && operator so the execution of echo "Command: "\'$command\'" does not exist" is skipped but the execution of the script continues till the end.
Note that the function_command_exists does not check if you have a right to execute the command. This needs to be done separately.
Solution with command -v <command-to-check>
#!/bin/sh
set -eu;
# check if a command exists (Yes)
command -v echo > /dev/null && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 1>"
fi
# check if a command exists (No)
command -v command-that-does-not-exists > /dev/null && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 2>"
fi
produces:
<handle not found 2>
because echo was found at the first example.
Solution with running a command and handling errors including command not found.
#!/bin/sh
set -eu;
# check if a command exists (No)
command -v command-that-does-not-exist > /dev/null && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 2>"
fi
# run command and handle errors (no problem expected, echo exist)
echo "three" && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 3>"
elif [ "${status}" -ne 0 ]; then
echo "<handle other error 3>"
fi
# run command and handle errors (<handle not found 4> expected)
command-that-does-not-exist && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 4>"
elif [ "${status}" -ne 0 ]; then
echo "<handle other error 4>"
fi
# run command and handle errors (command exists but <handle other error 5> expected)
ls non-existing-path && status="$?" || status="$?"
if [ "${status}" = 127 ]; then
echo "<handle not found 5>"
elif [ "${status}" -ne 0 ]; then
echo "<handle other error 5>"
fi
produces:
<handle not found 2>
three
./function_command_exists.sh: 34: ./function_command_exists.sh: command-that-does-not-exist: not found
<handle not found 4>
ls: cannot access 'non-existing-path': No such file or directory
<handle other error 5>
The following works in both bash and zsh and avoids both functions and aliases.
It returns 1 if the binary is not found.
bin_path () {
if [[ -n ${ZSH_VERSION:-} ]]; then
builtin whence -cp "$1" 2> /dev/null
else
builtin type -P "$1"
fi
}

Resources