Bourne Shell Script - sh

I'm attempting to write a script in the Bourne shell that will do the following:
Read in a filename
If the file does not exist in the target directory, it will display a message to the user stating such
If the file exists in the target directory, it will be moved to a /trash folder
If the file exists in the target directory, but a file of the same name is in the /trash folder, it will still move the file to the /trash directory, but will attach a _bak extention to the file.
My use of the Bourne shell is minimal, so here's what I have so far. Any pointers or tips would be greatly appreciated, thanks!
#!/bin/sh
#Scriptname: Trash Utility
source_dir=~/p6_tmp
target_dir=~/trash
echo "Please enter the filename you wish to trash:"
read filename
if [ -f $source_dir $filename]
then mv "$filename" "$target_dir"
else
echo "$filename does not exist"
fi

You cannot use ~ to refer to $HOME in a sh script. Switch to $HOME (or change the shebang to a shell which supports this, such as #!/bin/bash).
To refer to a file in a directory, join them with a slash:
if [ -f "$source_dir/$filename" ]
Notice also the required space before the terminating ] token.
To actually move the file you tested for, use the same expression for the source argument to mv:
mv "$source_dir/$filename" "$target_dir"
As a general design, a script which takes a command-line parameter is much easier to integrate into future scripts than one wich does interactive prompting. Most modern shells offer file name completion and history mechanisms, so a noninteractive script also tends to be more usable (you practically never need to transcribe a file name manually).

A Bash Solution:
#!/bin/bash
source_dir="~/p6_tmp"
target_dir="~/trash"
echo "Please enter the filename you wish to trash:"
read filename
if [ -f ${source_dir}/${filename} ]
then
if [ -f ${target_dir}/${filename} ]
then
mv "${source_dir}/${filename}" "${target_dir}/${filename}_bak"
else
mv "${source_dir}/${filename}" "$target_dir"
fi
else
echo "The file ${source_dir}/${filename} does not exist"
fi

Here's the completed script. Thanks again to all who helped!
#!/bin/sh
#Scriptname: Trash Utility
#Description: This script will allow the user to enter a filename they wish to send to the trash folder.
source_dir=~/p6_tmp
target_dir=~/trash
echo "Please enter the file you wish to trash:"
read filename
if [ -f "$source_dir/$filename" ]
then
if [ -f "$target_dir/$filename" ]
then mv "$source_dir/$filename" "$target_dir/$(basename "$filename")_bak"
date "+%Y-%m-%d %T - Trash renamed ~/$(basename "$source_dir")/$filename to ~/$(basename "/$target_dir")/$(basename "$filename")_bak" >> .trashlog
else mv "$source_dir/$filename" "$target_dir"
date "+%Y-%m-%d %T - Trash moved ~/$(basename "/$source_dir")/$filename to ~/$(basename "/$target_dir")/$filename" >> .trashlog
fi
else
date "+%Y-%m-%d %T - Trash of ~/$(basename "/$source_dir")/$filename does not exist" >> .trashlog
fi

Related

access failed error - no such file while trying to move files

I am trying to move all the *.csv files to another folder on server but every time i get access failed error , I am able to get all the files to local server using mget but mv fails everytime , i can see the file on the server and got full permissions on the files, sh script is not working with wild characters. struck here with the simple command .
Download to local directory
localDir="/home/toor/UCDownloads/"
[ ! -d $localDir ] && mkdir -p $localDir
#sftp in the file directory to be downloaded
remoteDir="/share/CACHEDEV1_DATA/Lanein1/Unicard/"
#The file to be downloaded is fileName
lftp -u ${sftp_user},${password} sftp://${host}:${port}<<EOF
PS4='$LINENO: '
set xfer:log true
set xfer:log-file "$logfileUCARC"
set xfer:clobber true
set xfer:auto-rename true
debug 9
cd ${remoteDir}
lcd ${localDir}
#mget *.CSV
ls -l
mv "/share/CACHEDEV1_DATA/Lanein1/Unicard/"*.csv "/share/CACHEDEV1_DATA/Lanein1/Unicard/Archives/"
#rm /share/CACHEDEV1_DATA/Lanein1/Unicard/!(*.pdf)
bye
EOF
This is not a shell or Bash problem. It is a LFTP problem.
From the manual of LFTP:
mv file1 file2
Rename file1 to file2. No wildcard expansion is performed.
LFTP just does not support what you asking for. It will treat *.csv as a part of the file name.
See here for an alternative.

sh Script with copy and removing a part from filename

So i use a script that copy's specific files to specific folders based on there filenames. I would like to extend the script so that after the copy progress a part from the filename is removed. Here is an example The filename looks likes this Image_000058_19_12_2019_1920x1080.jpg and i like to remove the resolution (_1920x1080) part from it. Is there a way to add it to my Script (see below) Thanks to #fedxc for the script.
cd "$HOME/Downloads"
# for filename in *; do
find . -type f | while IFS= read filename; do # Look for files in all ~/Download sub-dirs
case "${filename,,*}" in # this syntax emits the value in lowercase: ${var,,*} (bash version 4)
*.part) : ;; # Excludes *.part files from being moved
move.sh) : ;;
# *test*) mv "$filename" "$HOME/TVshows/Glee/" ;; # Using move there is no need to {&& rm "$filename"}
*test*) scp "$filename" "imac#imac.local:/users/imac/Desktop/" && rm "$filename" ;;
*american*dad*) scp "$filename" "imac#imac.local:/users/imac/Movies/Series/American\ Dad/" && rm "$filename" ;;
*) echo "Don't know where to put $filename" ;;
esac
done```
I use variable operation for bash. Example:
export filename='Image_000058_19_12_2019_1920x1080.jpg' <----Setting name of filename
echo ${filename/_1920x1080/} <--Operation with bash variable.
Image_000058_19_12_2019.jpg <--Result of echo
Consult this page for more: Bash Guide

Why can I save a .sh file as .txt and it still works when I run it

I have this in my myshellscript.txt:
#!/bin/sh
if [ -f $1 ]
then
cat $1
else
echo "Sorry, not found"
fi
Why is that even though it is a .txt file I can still run it using sh myshellscript.txt someotherfile.txt
Because you put a shebang (magic line) in the first line:
#!/bin/sh
This makes your shell know, it is a script it can run. At least if you made the file executable (chmod +x myshellscript.txt). UNIX does not care about file extensions as much as Windows does, so it does not depend on the file extension, whether a script is executable or not.

Is there a way to launch emacs merge without first opening emacs and using M-x and more?

I sometimes want to merge multiple pairs of files, suppose I want to merge fileA.old and fileA.new, as well as fileB.old and fileB.new..and so on.Currently I have to open emacs. Do M-x ediff-merge-files and enter name of first file, return key, name of second file, return key..and im in merge mode...is there a way to launch emacs with both file names as arguments and land in merge mode?
You can pass Lisp code to Emacs through the command line:
emacs --eval '(ediff-merge-files "path/to/file1" "path/to/file2")'
Of course this could be wrapped in a script to make it more convenient to call. For instance, in a bourne shell, you could do a simple version like this:
#!/bin/sh
# check correct invocation
if [ $# != 2 ]; then
echo "USAGE: $(basename "${0}") <file1> <file2>"
exit 1
fi
# check that file1 exists and is readable
if [ -f "${1}" ]; then
if [ ! -r "${1}" ]; then
echo "Cannot open '${1}', access denied."
exit 3
fi
else
echo "File not found: '${1}'"
exit 2
fi
# check that file2 exists and is readable
if [ -f "${2}" ]; then
if [ ! -r "${2}" ]; then
echo "Cannot open '${2}', access denied."
exit 5
fi
else
echo "File not found: '${2}'"
exit 4
fi
# invoke emacs
emacs --eval "(ediff-merge-files \"${1}\" \"${2}\")"
If you save this in a file ediff on your $PATH, you can then simply write:
ediff file1 file2
on the command line and Emacs will pop up with the two given files in ediff-mode.

How to compare the content of a tarball with a folder

How can I compare a tar file (already compressed) of the original folder with the original folder?
First I created archive file using
tar -kzcvf directory_name.zip directory_name
Then I tried to compare using
tar -diff -vf directory_name.zip directory_name
But it didn't work.
--compare (-d) is more handy for that.
tar --compare --file=archive-file.tar
works if archive-file.tar is in the directory it was created. To compare archive-file.tar against a remote target (eg if you have moved archive-file.tar to /some/where/) use the -C parameter:
tar --compare --file=archive-file.tar -C /some/where/
If you want to see tar working, use -v without -v only errors (missing files/folders) are reported.
Tipp: This works with compressed tar.bz/ tar.gz archives, too.
It should be --diff
Try this (without the last directory_name):
tar --diff -vf directory_name.zip
The problem is that the --diff command only looks for differences on the existing files among the tar file and the folder. So, if a new file is added to the folder, the diff command does not report this.
The method of pix is way slow for large compressed tar files, because it extracts each file individually. I use the tar --diff method loking for files with different modification time and extract and diff only these. The files are extracted into a folder base.orig where base is either the top level folder of the tar file or teh given comparison folder. This results in diffs including the date of the original file.
Here is the script:
#!/bin/bash
set -o nounset
# Print usage
if [ "$#" -lt 1 ] ; then
echo 'Diff a tar (or compressed tar) file with a folder'
echo 'difftar-folder.sh <tarfile> [<folder>] [strip]'
echo default for folder is .
echo default for strip is 0.
echo 'strip must be 0 or 1.'
exit 1
fi
# Parse parameters
tarfile=$1
if [ "$#" -ge 2 ] ; then
folder=$2
else
folder=.
fi
if [ "$#" -ge 3 ] ; then
strip=$3
else
strip=0
fi
# Get path prefix if --strip is used
if [ "$strip" -gt 0 ] ; then
prefix=`tar -t -f $tarfile | head -1`
else
prefix=
fi
# Original folder
if [ "$strip" -gt 0 ] ; then
orig=${prefix%/}.orig
elif [ "$folder" = "." ] ; then
orig=${tarfile##*/}
orig=./${orig%%.tar*}.orig
elif [ "$folder" = "" ] ; then
orig=${tarfile##*/}
orig=${orig%%.tar*}.orig
else
orig=$folder.orig
fi
echo $orig
mkdir -p "$orig"
# Make sure tar uses english output (for Mod time differs)
export LC_ALL=C
# Search all files with a deviating modification time using tar --diff
tar --diff -a -f "$tarfile" --strip $strip --directory "$folder" | grep "Mod time differs" | while read -r file ; do
# Substitute ': Mod time differs' with nothing
file=${file/: Mod time differs/}
# Check if file exists
if [ -f "$folder/$file" ] ; then
# Extract original file
tar -x -a -f "$tarfile" --strip $strip --directory "$orig" "$prefix$file"
# Compute diff
diff -u "$orig/$file" "$folder/$file"
fi
done
To ignore differences in some or all of the metadata (user, time, permissions), you can pipe the result to awk:
tar --compare --file=archive-file.tar -C /some/where/ | awk '!/Mode/ && !/Uid/ && !/Gid/ && !/time/'
That should output only the true differences between the tar and the directory /some/where/
I recently needed a better compare than what "tar --diff" produced so I made this short script:
#!/bin/bash
tar tf "$1" | while read ; do
if [ "${REPLY%/}" = "$REPLY" ] ; then
tar xOf "$1" "$REPLY" | diff -u - "$REPLY"
fi
done
The easy way is to write:
tar df file This compares the file with the current working directory, and tell us about if any of the files has been removed.
tar df file -C path/folder This compares the file with the folder.