Encrypt all files in dir using GPG

If you have your unencrypted files in a directory "unencrypted":

$ find unencrypted -type f
unencrypted/foo.conf
unencrypted/secret/bar.conf

You can write a wee bash function like this:

## $1 :: dir with files you want to encrypt
gpg_key=your.user@example.com

encrypt_files_in_dir() {
  local dir=$1
  find "${dir}" -type f -and -not -name "*.asc" |
    while read -r f; do
      gpg --encrypt --armour --yes --recipient "${gpg_key}" "${f}"
      target_dir=$(dirname "${f}" | sed 's#/unencrypted##')
      mkdir -p "${target_dir}"
      mv "${f}".asc "${target_dir}/."
    done
}

Then call it with a directory holding unencrypted files:

main() {
  encrypt_files_in_dir /path/to/unencrypted
}

This will encrypt all the files and put them in a similar structure:

$ find -type f
unencrypted/foo.conf
unencrypted/secret/bar.conf
foo.conf.asc
secret/bar.conf.asc

Nice, eh?


~ /home 🏠 ~ talks 💬 ~ bash ~ craftsmanship ~ db ~ dongxi ~ emacs ~ escenic ~ iam ~ java ~ js ~ language ~ latex ~ ldap ~ life ~ linux ~ llm ~ mac-os-x ~ mt-foo ~ network ~ norsk ~ python ~ quotes ~ running ~ security ~ travel ~ unix ~ various ~ vcs ~ webdesign ~ windows ~ discoveries ~ cv 🧙 ~

Licensed under CC BY Creative Commons License ~ 📡 RSS feed ~ ✉ torstein.k.johansen @ gmail ~ 🐘 @skybert@hachyderm.io ~ 🎥 youtube.com/@skybert