MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Shell Bash Scripting: Assignment & Excercise – 16

This exercise asks for a Bash script that packs a file or directory into a compressed tar archive and then encrypts it with a passphrase. The solution uses tar and gpg -c (GnuPG symmetric encryption). Below the original exercise you will find what each line does, a safer version that never writes an unencrypted archive to disk, how to decrypt and verify the result, and fixes for the usual errors.


Write a Shell Bash Script for archive a path into a file and encrypt the file


How the example script works

The gist above takes two positional arguments: an archive name ($1) and the path to archive ($2). It then runs three commands in order:

LineWhat it does
tar -czvf "$name.tar.gz" "$path"-c creates an archive, -z compresses it with gzip, -v lists each file as it is added, and -f sets the output file name.
gpg -c "$name.tar.gz"-c (--symmetric) encrypts with a passphrase instead of a public key. It asks for the passphrase twice and writes $name.tar.gz.gpg.
rm -rf "$name.tar.gz"Deletes the unencrypted archive so only the encrypted copy is left.

The approach is right, but the script has gaps. It does not check its arguments. It writes a plaintext archive to disk before encrypting it. And it runs rm even if encryption fails or the passphrase prompt is cancelled.

Prerequisites

  • A Linux or macOS shell with Bash and tar.
  • GnuPG installed. On Debian or Ubuntu run sudo apt install gnupg, on RHEL, Rocky or Fedora run sudo dnf install gnupg2, and on macOS run brew install gnupg.
  • Read access to the path you want to archive and write access to the current directory.
  • Run gpg --version to confirm that GnuPG is available.

A safer version of the script

This version checks its inputs and streams tar output straight into gpg, so no unencrypted archive is ever written to disk. It also refuses to overwrite an existing file and removes partial output if anything fails.

#!/usr/bin/env bash
# archive-and-encrypt.sh - archive a file or directory and encrypt it with a passphrase
# Usage: ./archive-and-encrypt.sh <archive-name> <path>
set -euo pipefail

usage() {
  echo "Usage: $0 <archive-name> <path>" >&2
  exit 1
}

[[ $# -eq 2 ]] || usage

name=$1
src=$2
out="${name}.tar.gz.gpg"

command -v gpg >/dev/null 2>&1 || { echo "Error: gpg is not installed" >&2; exit 2; }
[[ -e "$src" ]]  || { echo "Error: '$src' does not exist" >&2; exit 3; }
[[ ! -e "$out" ]] || { echo "Error: '$out' already exists" >&2; exit 4; }

# Remove a half-written output file if any command fails
trap 'rm -f -- "$out"' ERR

parent=$(dirname -- "$src")
base=$(basename -- "$src")

# -C stores paths relative to the parent directory instead of the full path
tar -czf - -C "$parent" "$base" \
  | gpg --symmetric --cipher-algo AES256 --output "$out"

trap - ERR
echo "Created $out"Code language: PHP (php)
  • set -euo pipefail stops the script on the first error or unset variable. pipefail makes the pipeline fail if tar fails, not only if gpg fails.
  • tar -czf - writes the archive to standard output. gpg reads it from standard input, so the plaintext only exists in memory.
  • -C "$parent" "$base" changes into the parent directory first. Running ./archive-and-encrypt.sh logs /var/log/nginx stores nginx/... instead of var/log/nginx/....
  • --cipher-algo AES256 makes the cipher explicit instead of relying on the default of the installed GnuPG version.
  • The ERR trap deletes an incomplete .gpg file, for example if you press Ctrl+C at the passphrase prompt.

Run, decrypt and verify

  1. Create some test data: mkdir -p demo && echo hello > demo/a.txt && echo world > demo/b.txt
  2. Make the script executable: chmod +x archive-and-encrypt.sh
  3. Run it: ./archive-and-encrypt.sh backup demo. Enter a passphrase twice when asked. The script prints Created backup.tar.gz.gpg.
  4. List the contents without extracting: gpg -d backup.tar.gz.gpg | tar -tzf -
  5. Extract into a separate directory: mkdir restore && gpg -d backup.tar.gz.gpg | tar -xzf - -C restore
  6. Compare with the original: diff -r demo restore/demo. No output means the files are identical.

Note: gpg-agent caches the passphrase for a few minutes, so decrypting right after encrypting may not ask for it. That does not mean the file is unprotected. To clear the cache, run gpgconf --reload gpg-agent.

If you used the original script, decrypt it to a normal archive first and then extract it:

gpg --output backup.tar.gz --decrypt backup.tar.gz.gpg
tar -xzvf backup.tar.gzCode language: CSS (css)

Running it non-interactively from cron or CI

A scheduled job has no terminal for the passphrase prompt. Store the passphrase in a file that only the job owner can read, and pass it in batch mode. Since GnuPG 2.1, --pinentry-mode loopback is needed for gpg to accept a passphrase this way.

# one-time setup
printf '%s' 'a-long-random-passphrase' > ~/.backup-pass
chmod 600 ~/.backup-pass

# in the script, replace the gpg line with:
tar -czf - -C "$parent" "$base" \
  | gpg --batch --yes --pinentry-mode loopback \
        --passphrase-file "$HOME/.backup-pass" \
        --symmetric --cipher-algo AES256 --output "$out"Code language: PHP (php)

Note: Never use --passphrase 'secret' on the command line. Other users can see the command line in ps output, and it is saved in your shell history. For backups that several people or systems must decrypt, public-key encryption (gpg --encrypt --recipient ...) avoids sharing a passphrase at all.

Common errors and fixes

Error or symptomCauseFix
gpg: command not foundGnuPG is not installed.Install the gnupg or gnupg2 package.
gpg: problem with the agent: Inappropriate ioctl for devicepinentry cannot find a terminal, which is common over SSH or inside scripts.Run export GPG_TTY=$(tty) first, or use the batch options shown above.
gpg: decryption failed: Bad session keyWrong passphrase.Re-enter the correct passphrase. Without it the data cannot be recovered.
tar: Removing leading '/' from member namesAn absolute path was passed to the original script.This is only a warning. Use -C as in the safer version to get clean relative paths.
File 'x.tar.gz.gpg' exists. Overwrite? (y/N)The output file is already there.Choose a new name, or add --yes if overwriting is intended.
Script creates a file named .tar.gzThe original script was run without arguments.Use the safer version, which validates its arguments.

Corrections to the original script

  • No input validation: running it without arguments creates a file called .tar.gz and fails in a confusing way. The safer version checks the argument count, that the path exists and that gpg is installed.
  • Unconditional delete: rm -rf runs even if gpg fails or is cancelled. Piping tar into gpg removes the need for a temporary file and for rm.
  • Plaintext on disk: the unencrypted .tar.gz sits on disk until it is deleted, and on most filesystems it can still be recovered after a plain rm. Streaming avoids this.
  • rm -rf for a single file: -r is unnecessary and risky in scripts. Use rm -f -- when a delete is really needed.
  • Full paths stored in the archive: passing /var/log/nginx stores var/log/nginx/.... tar -C stores only the last directory name.

Best practices for encrypted archives

  • Use a long, random passphrase and keep it in a password manager. If it is lost, the archive is lost.
  • Test a restore regularly. An encrypted backup that cannot be decrypted is worthless.
  • Add a timestamp to the name to keep versions, for example ./archive-and-encrypt.sh "backup-$(date +%F)" /etc.
  • Do not include secrets in the archive name, because file names are not encrypted.
  • For more practice, see Shell Bash Scripting: Assignment & Excercise – 3 and the Bash interview questions.

Frequently asked questions

How do I decrypt a .tar.gz.gpg file?

Run gpg -d file.tar.gz.gpg | tar -xzf - to decrypt and extract in one step. You can also run gpg -o file.tar.gz -d file.tar.gz.gpg and then extract the archive with tar -xzf.

Why did gpg not ask for my passphrase when decrypting?

gpg-agent caches recently used passphrases for a short time. Run gpgconf --reload gpg-agent to clear the cache and force a new prompt.

Is gpg -c secure enough for backups?

Yes. Symmetric GnuPG encryption with a strong passphrase and a modern cipher such as AES256 is a sound way to protect archives. The weak point is usually the passphrase, so make it long and random.

How can I encrypt an archive without typing a passphrase?

Use --batch --pinentry-mode loopback --passphrase-file with a file set to mode 600. Another option is public-key encryption with --encrypt --recipient, which needs no passphrase to encrypt.

Can I use zip -e instead of tar and gpg?

zip -e traditionally uses the legacy ZipCrypto scheme, which is considered weak. tar with gpg is the better choice for sensitive data on Linux.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals

Related Posts

Shell Scripting Tutorials: Conditional statatement using if

Bash makes decisions with if, if-else, if-elif-else, nested if and case. Each one runs a command or test and branches on its exit status. Below the original…

Read More

Best HIPAA-Compliant Software Development Companies in the USA

Quick Answer: Which Companies Lead HIPAA-Compliant Development in 2027? The best HIPAA-compliant software development company gets three things right. Impeccable security from day one, with access controls,…

Read More

Encryption using Public key and Private key in PHP using mySql database

This tutorial shows how to generate an RSA key pair with PHP's OpenSSL extension, encrypt form input with the public key, store the ciphertext in MySQL, and…

Read More

Encryption using RSA public and Private Key using PHP

PHP's OpenSSL extension can create an RSA key pair, encrypt data with the public key and decrypt it with the private key. This page explains the gist…

Read More

Shell Bash Scripting: Assignment & Excercise – 15

This exercise builds a Bash script that takes an IP address, sends it to the free ip-api.com geolocation API with curl, and uses jq to print the…

Read More

Shell script to git add and commit and push each directory at a time

This page shows how to use a Bash script to stage, commit and push changes one directory at a time. That can mean a folder full of…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x