Skip to content

Instantly share code, notes, and snippets.

@ffledgling
Created September 4, 2015 16:29
Show Gist options
  • Select an option

  • Save ffledgling/23aa94e2806d71f96797 to your computer and use it in GitHub Desktop.

Select an option

Save ffledgling/23aa94e2806d71f96797 to your computer and use it in GitHub Desktop.
File descriptor demo; bash; How to isolate and collect error messages for particular from function calls, across subshells etc.
#!/bin/bash
# Create file to accumulate errors
errfile=$(mktemp)
echo "Error File is ${errfile}"
# Have fd 3 point to where fd 2 points currently
exec 3>&2
# wrapper function
grup () {
# Change fd 2 to point to some file we create
# Use >> to append to file, so that it's not truncated everytime function is called
exec 2>> ${errfile}
# command that throws the errors; errors are collected regardless of
$(grep $@ )
# Close 2, so it no longer points to a file
exec 2>&-
# restore normal function for stderr
exec 2>&3
}
# Call some functions that generate errors
for opt in '--wrong-arg' '--no-such-arg' '--nooope' ; do
grup $opt
done
# Another wrong call to show resoration of stderr outside function
grep --woops
#echo -e '\nWaiting 2s and showing errors in one go:\n\n'
#sleep 1 && cat $errfile
echo "To see the other errors, run cat ${errfile}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment