Skip to content

Instantly share code, notes, and snippets.

@xbalaji
Created September 17, 2022 16:34
Show Gist options
  • Save xbalaji/d4cd345e2ecff98b0c0ae6e63bbdffc0 to your computer and use it in GitHub Desktop.
Save xbalaji/d4cd345e2ecff98b0c0ae6e63bbdffc0 to your computer and use it in GitHub Desktop.
redirect-and-exitstatus.sh
#! /usr/bin/env bash
# reference: https://superuser.com/questions/1179844/what-does-dev-null-21-true-mean-in-linux
# usage:
# stdout, stderr seen on the console, there should be no error
# ./redirect-and-exitstatus.sh redirect-and-exitstatus.sh
#
# stderr seen on the console, if not captured in the program
# ./redirect-and-exitstatus.sh <non-existent-file>
#
# stderr redirected to null, console stays clean
# ./redirect-and-exitstatus.sh <non-existent-file> 2>/dev/null
#
# no redirection
# returns exit status; stdout and stderr are not redirected
r1=$(ls $1)
echo "r1: exit status: $?, output of the command: $r1"
# redirects only stdout to null
# returns exit status; stdout goes to null; stderr is not redirected
r2=$(ls $1 > /dev/null)
echo "r2: exit status: $?, output of the command: $r2"
# redirects stdout to null, stderr to stdout,
# returns exit status; stdout goes to null; stderr goes to stdout (null)
r3=$(ls $1 > /dev/null 2>&1)
echo "r3: exit status: $?, output of the command: $r3"
# exit status set to 0; stdout and stderr goes to null
r4=$(ls $1 > /dev/null 2>&1 || true)
echo "r4: exit status: $?, output of the command: $r4"
# returns exit status; stdout and stderr goes to null
r5=$(ls $1 &> /dev/null) # short form of r3
echo "r5: exit status: $?, output of the command: $r5"
# exit status set to 0; stdout and stderr goes to null
r6=$(ls $1 &> /dev/null || true) # short form of r4
echo "r6: exit status: $?, output of the command: $r6"
# returns exit status; stderr redirected to stdout, output as-is
r7=$(ls $1 2>&1)
echo "r7: exit status: $?, output of the command: $r7"
# exit status set to 0; stderr redirected to stdout, output as-is
# useful for commands which have no output on success
# on failure there is some noise in the output (stderr), that is captured
#
# consider the output of gcc, for successful execution there is no output
# gcc <succesful-compliation> --> no output
# gcc <failing-compliation> --> stderr or stdout has some noise
#
# echo "void main(){}" > a.c; gcc a.c
r8=$(ls $1 2>&1 || true)
echo "r8: exit status: $?, output of the command: $r8"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment