diff options
author | Tom Ryder <tom@sanctum.geek.nz> | 2015-10-12 14:28:04 +1300 |
---|---|---|
committer | Tom Ryder <tom@sanctum.geek.nz> | 2015-10-12 14:28:04 +1300 |
commit | 22da15a9ffd7d33c72272302248d27d042afd427 (patch) | |
tree | 7d73750d16743775fe2087fe2b304c1c68d82899 /bash/bashrc.d | |
parent | Add options terminator to scr() mktemp(1) call (diff) | |
download | dotfiles-22da15a9ffd7d33c72272302248d27d042afd427.tar.gz dotfiles-22da15a9ffd7d33c72272302248d27d042afd427.zip |
New function fnl()
Diffstat (limited to 'bash/bashrc.d')
-rw-r--r-- | bash/bashrc.d/fnl.bash | 45 |
1 files changed, 45 insertions, 0 deletions
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" +} + |