Reputation: 91
TIA in advance for any help. This is coursework so further reading is always appreciated!
Basically I have to write 3 scripts in bash. One to 'delete' a file to a directory of my creation (~/rubbish). Another to restore it if needs be and a third to permanently delete it.
I'm kinda stuck on my trash script. It doesn't seem to be actually deleting anything as ls shows all the files still there. I am also having trouble with the flag (-a) that I have added for the user to trash all at once, IF not then it should ask confirmation for each file found.
Here's where I am just now...
#!/bin/bash
if [ "$1" = "-a" ]
then
cd ~/rubbish
rm ~/rubbish
mkdir ~/rubbish
echo "All files have been deleted"
else
cd ~/rubbish
ls > rubbish
for line in 'cat rubbish'
do
echo "Do you want to delete?" $line
echo "Y/N"
read ans
case "ans" in
Y|y ) rm $line;;
N|n ) " ";;
esac
done
fi
As I said, it doesn't see -a , and it skips the first branch and runs through the second seemingly fine, but when I ls ~/rubbish all the files are still there.
EDIT Thanks for the help guys! Sputnik, erm couldn't really see what you had changed in your comment other than adding semi colons? And inductiveLoad, your answer was ace, but I couldn't find a way to work it properly, lost patience and went uber basic. Like so....
#!/bin/bash
if [ "$1" = "-a" ] ;
then
cd ~/rubbish;
rm ~/rubbish/*;
echo "All files have been deleted";
else
rm -i ~/rubbish/* ;
fi
Upvotes: 1
Views: 1800
Reputation: 6372
I would use getopts
to parse options, as it allows much more flexibility, any number of arbitrarily ordered arguments, options with data (as opposed to a flag - see the -d
option below) and also prints help if you give bad options.
usage()
{
cat <<EOF
usage: $0 options
This script deletes/restores/trashes files.
OPTIONS:
-h Show this message
-a Trash it all!
-d Rubbish directory
EOF
}
trashAll=false
rubbishDir="~/rubbish"
while getopts "ad:" OPTION;
do
case "$OPTION"
in
h) usage
exit 1;;
a) trashAll=true;;
d) rubbishDir=${OPTARG};;
?) usage
exit 1;;
esac
done
if $trashAll
then
#trash it all
echo "Trashing all in ${rubbishDir}!"
fi
Upvotes: 2