ShellCheck SC2069 -- Correct Ordering of Redirections

The Problem

ShellCheck warning:

SC2069: To redirect stdout+stderr, 2>&1 must be last.

Example of incorrect code:

ping -c 1 10.0.1."$names" 2>&1 >/dev/null

This does not send both stdout and stderr to /dev/null.

Why?

Redirections are processed left to right.

The shell first executes:

2>&1

which makes stderr point to the current destination of stdout (normally the terminal).

It then executes:

>/dev/null

which changes only stdout to /dev/null.

The result is:

  • stdout → /dev/null
  • stderr → terminal

Correct Solution

If you want to discard both stdout and stderr:

ping -c 1 10.0.1."$names" >/dev/null 2>&1

or

ping -c 1 10.0.1."$names" &>/dev/null

(Bash only.)

Rules to Remember

  • Redirect stdout first.
  • Redirect stderr second.
  • 2>&1 should almost always be the last redirection.

Good:

command >/dev/null 2>&1
command >file 2>&1
command >>file 2>&1

Bad:

command 2>&1 >/dev/null
command 2>&1 >file
command 2>&1 >>file

Quick Mental Model

Think of 2>&1 as:

"Make stderr go wherever stdout is going right now."

If stdout changes afterwards, stderr does not automatically follow.

Checklist

Before writing a command:

  • Where should stdout go?
  • Redirect stdout there.
  • Finish with 2>&1 if stderr should follow stdout.

This ordering avoids SC2069 and works consistently across POSIX shells.