From 22da15a9ffd7d33c72272302248d27d042afd427 Mon Sep 17 00:00:00 2001 From: Tom Ryder Date: Mon, 12 Oct 2015 14:28:04 +1300 Subject: New function fnl() --- bash/bashrc.d/fnl.bash | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 bash/bashrc.d/fnl.bash (limited to 'bash/bashrc.d') diff --git a/bash/bashrc.d/fnl.bash b/bash/bashrc.d/fnl.bash new file mode 100644 index 00000000..09d1af61 --- /dev/null +++ b/bash/bashrc.d/fnl.bash @@ -0,0 +1,45 @@ +# Run a command and push its stdout and stderr into temporary files, printing +# the names of the files once done, and saving them into two variables. Return +# the exit status of the command. +# +# $ fnl grep foo /bar +# declare -- fnl_stdout="/tmp/fnl.xQmhe/stdout" +# declare -- fnl_stderr="/tmp/fnl.xQmhe/stderr" +# +fnl() { + + # Must be called with at least one command argument + if ! (($#)) ; then + printf 'bash: %s: usage: %s COMMAND [ARG1 ...]\n' \ + "$FUNCNAME" "$FUNCNAME" >&2 + return 2 + fi + + # Try to stop infinitely recursive calls + if [[ $1 == "$FUNCNAME" ]] ; then + printf 'bash: %s: Cannot nest calls\n' \ + "$FUNCNAME" >&2 + return 2 + fi + + # Create a temporary directory or bail + local template dir + template=$FUNCNAME.$1.XXXXX + if ! dir=$(mktemp -dt -- "$template") ; then + return + fi + + # Run the command and save its exit status + local ret + command "$@" >"$dir"/stdout 2>"$dir"/stderr + ret=$? + + # Note these are *not* local variables + # shellcheck disable=SC2034 + fnl_stdout=$dir/stdout fnl_stderr=$dir/stderr + declare -p fnl_std{out,err} + + # Return the exit status of the command, not the declare builtin + return "$ret" +} + -- cgit v1.2.3