Reputation: 84
I've been writing some code to (mostly) automate password protecting and compressing/archiving folders and files. However, the code seems to hate me.
I've run it line by line, and it always chokes on the zip command, even when the $file
and $source
are correct and valid.
Any ideas?
Here's the source code:
#!/bin/bash
echo "Drag in the source file"
read source
echo
echo "Drag in the destination file, or press enter to select the Desktop"
read destination
echo
if [ -z "$destination" ]
then destination="$PWD/Desktop"
echo "Destination is set to the desktop"
fi
echo "Type the name of the file to make"
read file
if [ -z "$file" ]
then file="archive"
echo "File name set to archive.zip"
fi
file="${destination}/${file}"
if [ -d $"source" ]
then zip -erj "$file" "$destination"
else zip -ej "$file" "$destination"
fi
Upvotes: 4
Views: 13501
Reputation: 72376
There are a couple of problems in your code:
if [ -z "$destination" ]
then destination="$PWD/Desktop"
echo "Destination is set to the desktop"
fi
$PWD
is the current working directory. It is your home directory when you open a Terminal but it changes everytime you run cd
.
The Desktop directory is $HOME/Desktop
.
If you don't run the script from your home directory, most probably $PWD/Desktop
doesn't exist and this is a cause for errors; zip
doesn't attempt to create the destination directory for the archive you ask it to build. If the directory doesn't already exist it displays an error message and exits.
Another problem is on the invocation of zip
:
if [ -d $"source" ]
then zip -erj "$file" "$destination"
else zip -ej "$file" "$destination"
fi
You probably want to archive the file $source
or the files in the $source
directory (if it is a directory) but you mistakenly put $destination
as the file/directory to archive in the zip
command line.
if [ -d $"source" ]
-- it should be "$source"
, otherwise the quote are useless and if $source
contains spaces the script will exit with a syntax error.
One last thing: zip
doesn't mind receiving -r
in the command line when it is asked to archive only one file. You can replace the entire if/else
block above with a single command:
zip -erj "$file" "$source"
Upvotes: 4