Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Pipe or Redirect Case Statement Result in a Shell Script

pipe-or-redirect-case-statement-result-in-a-shell-script.jpg

This can help reduce duplication in your scripts.

Quick Jump:

In your shell you can pipe the output of another program as input into another, such as running echo "A,B,C" | cut -d "," -f 1 to return A.

I had a use case come up recently where I had a case statement and I wanted to pipe the result of that to another tool.

Basically I had 4 different cases that did different things but I wanted all of them to be piped to the same program with a couple of flags and options being set to the same thing. This helped prevent copy / pasting that same program 4 different times.

Turns out there’s nothing special to do, you can pipe it, here’s an example:

#!/usr/bin/env bash

set -o errexit
set -o pipefail
set -o nounset

MODE="${1}"

case "${MODE}" in
letter)
  echo "A,B,C"
  ;;
color)
  echo "Red,Green,Blue"
  ;;
*)
  echo "Mode is not available: ${MODE}" >&2
  exit 1
  ;;
esac | cut -d "," -f 1

Here’s a couple of outputs:

$ ./demo letter
A
$ ./demo color
Red

It wasn’t immediately obvious to me that this was possible but it makes sense. When a case statement executes, it’s picking one of the options to run which in this example produces stdout (echo) which we pipe into cut. In the error case we exit early so the pipe never runs.

What’s nice is this also works for redirecting too. Instead of doing esac | cut -d "," -f 1 you can do something like esac 2> /dev/null || true if you wanted to hide all errors from your case commands and make sure your script always runs successfully.

The video below shows what we covered above.

# Demo Video

Timestamps

  • 0:22 – Pipe a case statement to another program
  • 1:18 – It’s also handy for redirecting

When was the last time you ended up doing this? Let me know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments