Automated Recursive Encryption in a Directory Using Shell Script
Last Updated :
21 Nov, 2019
This script would encrypt file provided as an argument or a directory and its constituent files and sub-directories recursively. It would be very useful for automating the encryption of multiple files in a directory all together.
How it works?
- If no arguments are given, throw an error and exit the program.
- Read the password to use for encrypting the files in a variable.
- Find the path of the given argument by realpath.
- Create a function to check the provided argument is a directory or a file.
- If a directory is given, get the files recursively under that directory and sort and remove the duplicate entries in the files list by ls | uniq and store it in an array.
- Pass the output of ls | uniq to the function one by one by indices of the created array in a loop i.e calling the same function recursively.
- If a file a is given, do step 8
- Loop through each file and encrypt the file with the builtin ‘gpg‘ utility with the given password.
- If the ‘gpg‘ utility exits with a non-zero exit code, throw the error message and end the program. Else delete the original file and show the encrypted file’s name to indicate that it is successfully encrypted.
Source Code: You can use any editor on Linux like nano and save this as s1.sh. You may face some problems with the permission of this file while executing this shell script. Don’t worry, just use the command sudo chmod 774 s1.sh to come over this problem.
#!/bin/bash
if [ -z "$1" ]; then
echo "No file provided" >&2
exit 1
fi
read -p "Enter the password" pass
function func()
{
file_name=$1
if [ -d `realpath $file_name` ]; then
cd `realpath $file_name`
array=(` ls | uniq `)
len=${
i=0
while [ $i -lt $len ]; do
echo "${array[$i]}"
func ${array[$i]}
let i++
done
fi
if [ -f `realpath $file_name` ]; then
test = echo $pass | gpg -c --batch -- yes --passphrase-fd 0 $file_name
if [ "$test" == "1" ]; then
echo "Bad signature: gpg not executed properly" >&2
exit 1
elif [ "$test" == "2" ]; then
echo "unexpected error: gpg not executed properly" >&2
exit 1
else
rm $file_name
echo " $file_name.gpg "
fi
fi
}
func $1
|
Output:
Share your thoughts in the comments
Please Login to comment...