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:
| Line | What 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 runsudo dnf install gnupg2, and on macOS runbrew install gnupg. - Read access to the path you want to archive and write access to the current directory.
- Run
gpg --versionto 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 pipefailstops the script on the first error or unset variable.pipefailmakes the pipeline fail iftarfails, not only ifgpgfails.tar -czf -writes the archive to standard output.gpgreads 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/nginxstoresnginx/...instead ofvar/log/nginx/....--cipher-algo AES256makes the cipher explicit instead of relying on the default of the installed GnuPG version.- The
ERRtrap deletes an incomplete.gpgfile, for example if you press Ctrl+C at the passphrase prompt.
Run, decrypt and verify
- Create some test data:
mkdir -p demo && echo hello > demo/a.txt && echo world > demo/b.txt - Make the script executable:
chmod +x archive-and-encrypt.sh - Run it:
./archive-and-encrypt.sh backup demo. Enter a passphrase twice when asked. The script printsCreated backup.tar.gz.gpg. - List the contents without extracting:
gpg -d backup.tar.gz.gpg | tar -tzf - - Extract into a separate directory:
mkdir restore && gpg -d backup.tar.gz.gpg | tar -xzf - -C restore - 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 symptom | Cause | Fix |
|---|---|---|
gpg: command not found | GnuPG is not installed. | Install the gnupg or gnupg2 package. |
gpg: problem with the agent: Inappropriate ioctl for device | pinentry 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 key | Wrong passphrase. | Re-enter the correct passphrase. Without it the data cannot be recovered. |
tar: Removing leading '/' from member names | An 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.gz | The 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.gzand fails in a confusing way. The safer version checks the argument count, that the path exists and thatgpgis installed. - Unconditional delete:
rm -rfruns even ifgpgfails or is cancelled. Pipingtarintogpgremoves the need for a temporary file and forrm. - Plaintext on disk: the unencrypted
.tar.gzsits on disk until it is deleted, and on most filesystems it can still be recovered after a plainrm. Streaming avoids this. rm -rffor a single file:-ris unnecessary and risky in scripts. Userm -f --when a delete is really needed.- Full paths stored in the archive: passing
/var/log/nginxstoresvar/log/nginx/....tar -Cstores 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
- More Shell Scripting tutorials
- What is Bash and use cases of Bash?
- Shell Bash Scripting Interview Questions and Answer – Part 4
- Shell Bash Scripting: Assignment & Excercise – 3
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals