{"id":32388,"date":"2026-11-30T22:08:05","date_gmt":"2026-11-30T22:08:05","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=32388"},"modified":"2026-11-30T22:08:05","modified_gmt":"2026-11-30T22:08:05","slug":"shell-bash-scripting-assignment-excercise-16","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/shell-bash-scripting-assignment-excercise-16\/","title":{"rendered":"Shell Bash Scripting: Assignment &amp; Excercise \u2013 16"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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 <code>tar<\/code> and <code>gpg -c<\/code> (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.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">Write a Shell Bash Script for archive a path into a file and encrypt the file\n<\/code><\/span><\/pre>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/fe1ddd1fe0a98402fd974990c7b2fab1.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How the example script works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The gist above takes two positional arguments: an archive name (<code>$1<\/code>) and the path to archive (<code>$2<\/code>). It then runs three commands in order:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Line<\/th><th>What it does<\/th><\/tr><\/thead><tbody><tr><td><code>tar -czvf &quot;$name.tar.gz&quot; &quot;$path&quot;<\/code><\/td><td><code>-c<\/code> creates an archive, <code>-z<\/code> compresses it with gzip, <code>-v<\/code> lists each file as it is added, and <code>-f<\/code> sets the output file name.<\/td><\/tr><tr><td><code>gpg -c &quot;$name.tar.gz&quot;<\/code><\/td><td><code>-c<\/code> (<code>--symmetric<\/code>) encrypts with a passphrase instead of a public key. It asks for the passphrase twice and writes <code>$name.tar.gz.gpg<\/code>.<\/td><\/tr><tr><td><code>rm -rf &quot;$name.tar.gz&quot;<\/code><\/td><td>Deletes the unencrypted archive so only the encrypted copy is left.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>rm<\/code> even if encryption fails or the passphrase prompt is cancelled.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A Linux or macOS shell with Bash and <code>tar<\/code>.<\/li>\n\n\n<li>GnuPG installed. On Debian or Ubuntu run <code>sudo apt install gnupg<\/code>, on RHEL, Rocky or Fedora run <code>sudo dnf install gnupg2<\/code>, and on macOS run <code>brew install gnupg<\/code>.<\/li>\n\n\n<li>Read access to the path you want to archive and write access to the current directory.<\/li>\n\n\n<li>Run <code>gpg --version<\/code> to confirm that GnuPG is available.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">A safer version of the script<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This version checks its inputs and streams <code>tar<\/code> output straight into <code>gpg<\/code>, so no unencrypted archive is ever written to disk. It also refuses to overwrite an existing file and removes partial output if anything fails.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">#!\/usr\/bin\/env bash<\/span>\n<span class=\"hljs-comment\"># archive-and-encrypt.sh - archive a file or directory and encrypt it with a passphrase<\/span>\n<span class=\"hljs-comment\"># Usage: .\/archive-and-encrypt.sh &lt;archive-name&gt; &lt;path&gt;<\/span>\nset -euo pipefail\n\nusage() {\n  <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Usage: $0 &lt;archive-name&gt; &lt;path&gt;\"<\/span> &gt;&amp;<span class=\"hljs-number\">2<\/span>\n  <span class=\"hljs-keyword\">exit<\/span> <span class=\"hljs-number\">1<\/span>\n}\n\n&#91;&#91; $<span class=\"hljs-comment\"># -eq 2 ]] || usage<\/span>\n\nname=$<span class=\"hljs-number\">1<\/span>\nsrc=$<span class=\"hljs-number\">2<\/span>\nout=<span class=\"hljs-string\">\"${name}.tar.gz.gpg\"<\/span>\n\ncommand -v gpg &gt;\/dev\/<span class=\"hljs-keyword\">null<\/span> <span class=\"hljs-number\">2<\/span>&gt;&amp;<span class=\"hljs-number\">1<\/span> || { <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Error: gpg is not installed\"<\/span> &gt;&amp;<span class=\"hljs-number\">2<\/span>; <span class=\"hljs-keyword\">exit<\/span> <span class=\"hljs-number\">2<\/span>; }\n&#91;&#91; -e <span class=\"hljs-string\">\"$src\"<\/span> ]]  || { <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Error: '$src' does not exist\"<\/span> &gt;&amp;<span class=\"hljs-number\">2<\/span>; <span class=\"hljs-keyword\">exit<\/span> <span class=\"hljs-number\">3<\/span>; }\n&#91;&#91; ! -e <span class=\"hljs-string\">\"$out\"<\/span> ]] || { <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Error: '$out' already exists\"<\/span> &gt;&amp;<span class=\"hljs-number\">2<\/span>; <span class=\"hljs-keyword\">exit<\/span> <span class=\"hljs-number\">4<\/span>; }\n\n<span class=\"hljs-comment\"># Remove a half-written output file if any command fails<\/span>\ntrap <span class=\"hljs-string\">'rm -f -- \"$out\"'<\/span> ERR\n\n<span class=\"hljs-keyword\">parent<\/span>=$(dirname -- <span class=\"hljs-string\">\"$src\"<\/span>)\nbase=$(basename -- <span class=\"hljs-string\">\"$src\"<\/span>)\n\n<span class=\"hljs-comment\"># -C stores paths relative to the parent directory instead of the full path<\/span>\ntar -czf - -C <span class=\"hljs-string\">\"$parent\"<\/span> <span class=\"hljs-string\">\"$base\"<\/span> \\\n  | gpg --symmetric --cipher-algo AES256 --output <span class=\"hljs-string\">\"$out\"<\/span>\n\ntrap - ERR\n<span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Created $out\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>set -euo pipefail<\/code> stops the script on the first error or unset variable. <code>pipefail<\/code> makes the pipeline fail if <code>tar<\/code> fails, not only if <code>gpg<\/code> fails.<\/li>\n\n\n<li><code>tar -czf -<\/code> writes the archive to standard output. <code>gpg<\/code> reads it from standard input, so the plaintext only exists in memory.<\/li>\n\n\n<li><code>-C &quot;$parent&quot; &quot;$base&quot;<\/code> changes into the parent directory first. Running <code>.\/archive-and-encrypt.sh logs \/var\/log\/nginx<\/code> stores <code>nginx\/...<\/code> instead of <code>var\/log\/nginx\/...<\/code>.<\/li>\n\n\n<li><code>--cipher-algo AES256<\/code> makes the cipher explicit instead of relying on the default of the installed GnuPG version.<\/li>\n\n\n<li>The <code>ERR<\/code> trap deletes an incomplete <code>.gpg<\/code> file, for example if you press Ctrl+C at the passphrase prompt.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Run, decrypt and verify<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create some test data: <code>mkdir -p demo &amp;&amp; echo hello &gt; demo\/a.txt &amp;&amp; echo world &gt; demo\/b.txt<\/code><\/li>\n\n\n<li>Make the script executable: <code>chmod +x archive-and-encrypt.sh<\/code><\/li>\n\n\n<li>Run it: <code>.\/archive-and-encrypt.sh backup demo<\/code>. Enter a passphrase twice when asked. The script prints <code>Created backup.tar.gz.gpg<\/code>.<\/li>\n\n\n<li>List the contents without extracting: <code>gpg -d backup.tar.gz.gpg | tar -tzf -<\/code><\/li>\n\n\n<li>Extract into a separate directory: <code>mkdir restore &amp;&amp; gpg -d backup.tar.gz.gpg | tar -xzf - -C restore<\/code><\/li>\n\n\n<li>Compare with the original: <code>diff -r demo restore\/demo<\/code>. No output means the files are identical.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> 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 <code>gpgconf --reload gpg-agent<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you used the original script, decrypt it to a normal archive first and then extract it:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-tag\">gpg<\/span> <span class=\"hljs-selector-tag\">--output<\/span> <span class=\"hljs-selector-tag\">backup<\/span><span class=\"hljs-selector-class\">.tar<\/span><span class=\"hljs-selector-class\">.gz<\/span> <span class=\"hljs-selector-tag\">--decrypt<\/span> <span class=\"hljs-selector-tag\">backup<\/span><span class=\"hljs-selector-class\">.tar<\/span><span class=\"hljs-selector-class\">.gz<\/span><span class=\"hljs-selector-class\">.gpg<\/span>\n<span class=\"hljs-selector-tag\">tar<\/span> <span class=\"hljs-selector-tag\">-xzvf<\/span> <span class=\"hljs-selector-tag\">backup<\/span><span class=\"hljs-selector-class\">.tar<\/span><span class=\"hljs-selector-class\">.gz<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Running it non-interactively from cron or CI<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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, <code>--pinentry-mode loopback<\/code> is needed for <code>gpg<\/code> to accept a passphrase this way.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># one-time setup<\/span>\nprintf <span class=\"hljs-string\">'%s'<\/span> <span class=\"hljs-string\">'a-long-random-passphrase'<\/span> &gt; ~\/.backup-pass\nchmod <span class=\"hljs-number\">600<\/span> ~\/.backup-pass\n\n<span class=\"hljs-comment\"># in the script, replace the gpg line with:<\/span>\ntar -czf - -C <span class=\"hljs-string\">\"$parent\"<\/span> <span class=\"hljs-string\">\"$base\"<\/span> \\\n  | gpg --batch --yes --pinentry-mode loopback \\\n        --passphrase-file <span class=\"hljs-string\">\"$HOME\/.backup-pass\"<\/span> \\\n        --symmetric --cipher-algo AES256 --output <span class=\"hljs-string\">\"$out\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Never use <code>--passphrase &#039;secret&#039;<\/code> on the command line. Other users can see the command line in <code>ps<\/code> output, and it is saved in your shell history. For backups that several people or systems must decrypt, public-key encryption (<code>gpg --encrypt --recipient ...<\/code>) avoids sharing a passphrase at all.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Error or symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>gpg: command not found<\/code><\/td><td>GnuPG is not installed.<\/td><td>Install the <code>gnupg<\/code> or <code>gnupg2<\/code> package.<\/td><\/tr><tr><td><code>gpg: problem with the agent: Inappropriate ioctl for device<\/code><\/td><td>pinentry cannot find a terminal, which is common over SSH or inside scripts.<\/td><td>Run <code>export GPG_TTY=$(tty)<\/code> first, or use the batch options shown above.<\/td><\/tr><tr><td><code>gpg: decryption failed: Bad session key<\/code><\/td><td>Wrong passphrase.<\/td><td>Re-enter the correct passphrase. Without it the data cannot be recovered.<\/td><\/tr><tr><td><code>tar: Removing leading &#039;\/&#039; from member names<\/code><\/td><td>An absolute path was passed to the original script.<\/td><td>This is only a warning. Use <code>-C<\/code> as in the safer version to get clean relative paths.<\/td><\/tr><tr><td><code>File &#039;x.tar.gz.gpg&#039; exists. Overwrite? (y\/N)<\/code><\/td><td>The output file is already there.<\/td><td>Choose a new name, or add <code>--yes<\/code> if overwriting is intended.<\/td><\/tr><tr><td>Script creates a file named <code>.tar.gz<\/code><\/td><td>The original script was run without arguments.<\/td><td>Use the safer version, which validates its arguments.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Corrections to the original script<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No input validation:<\/strong> running it without arguments creates a file called <code>.tar.gz<\/code> and fails in a confusing way. The safer version checks the argument count, that the path exists and that <code>gpg<\/code> is installed.<\/li>\n\n\n<li><strong>Unconditional delete:<\/strong> <code>rm -rf<\/code> runs even if <code>gpg<\/code> fails or is cancelled. Piping <code>tar<\/code> into <code>gpg<\/code> removes the need for a temporary file and for <code>rm<\/code>.<\/li>\n\n\n<li><strong>Plaintext on disk:<\/strong> the unencrypted <code>.tar.gz<\/code> sits on disk until it is deleted, and on most filesystems it can still be recovered after a plain <code>rm<\/code>. Streaming avoids this.<\/li>\n\n\n<li><strong><code>rm -rf<\/code> for a single file:<\/strong> <code>-r<\/code> is unnecessary and risky in scripts. Use <code>rm -f --<\/code> when a delete is really needed.<\/li>\n\n\n<li><strong>Full paths stored in the archive:<\/strong> passing <code>\/var\/log\/nginx<\/code> stores <code>var\/log\/nginx\/...<\/code>. <code>tar -C<\/code> stores only the last directory name.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices for encrypted archives<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use a long, random passphrase and keep it in a password manager. If it is lost, the archive is lost.<\/li>\n\n\n<li>Test a restore regularly. An encrypted backup that cannot be decrypted is worthless.<\/li>\n\n\n<li>Add a timestamp to the name to keep versions, for example <code>.\/archive-and-encrypt.sh &quot;backup-$(date +%F)&quot; \/etc<\/code>.<\/li>\n\n\n<li>Do not include secrets in the archive name, because file names are not encrypted.<\/li>\n\n\n<li>For more practice, see <a href=\"https:\/\/www.devopsschool.com\/blog\/test-your-shell-scripting-skills-program-4\/\">Shell Bash Scripting: Assignment &amp; Excercise \u2013 3<\/a> and the <a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-interview-question-and-answers-of-bash-scripting\/\">Bash interview questions<\/a>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">How do I decrypt a .tar.gz.gpg file?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Run <code>gpg -d file.tar.gz.gpg | tar -xzf -<\/code> to decrypt and extract in one step. You can also run <code>gpg -o file.tar.gz -d file.tar.gz.gpg<\/code> and then extract the archive with <code>tar -xzf<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why did gpg not ask for my passphrase when decrypting?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">gpg-agent caches recently used passphrases for a short time. Run <code>gpgconf --reload gpg-agent<\/code> to clear the cache and force a new prompt.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is gpg -c secure enough for backups?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How can I encrypt an archive without typing a passphrase?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>--batch --pinentry-mode loopback --passphrase-file<\/code> with a file set to mode 600. Another option is public-key encryption with <code>--encrypt --recipient<\/code>, which needs no passphrase to encrypt.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I use zip -e instead of tar and gpg?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>zip -e<\/code> traditionally uses the legacy ZipCrypto scheme, which is considered weak. <code>tar<\/code> with <code>gpg<\/code> is the better choice for sensitive data on Linux.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/shell-script\/\">More Shell Scripting tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/what-is-bash-and-use-cases-of-bash\/\">What is Bash and use cases of Bash?<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-interview-question-and-answers-of-bash-scripting\/\">Shell Bash Scripting Interview Questions and Answer \u2013 Part 4<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/test-your-shell-scripting-skills-program-4\/\">Shell Bash Scripting: Assignment &amp; Excercise \u2013 3<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[454],"tags":[137,9450],"class_list":["post-32388","post","type-post","status-publish","format-standard","hentry","category-shell-script","tag-bash","tag-encryption"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/32388","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=32388"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/32388\/revisions"}],"predecessor-version":[{"id":80461,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/32388\/revisions\/80461"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=32388"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=32388"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=32388"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}