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 | |
parent | Add options terminator to scr() mktemp(1) call (diff) | |
download | dotfiles-22da15a9ffd7d33c72272302248d27d042afd427.tar.gz dotfiles-22da15a9ffd7d33c72272302248d27d042afd427.zip |
New function fnl()
-rw-r--r-- | README.markdown | 1 | ||||
-rw-r--r-- | bash/bashrc.d/fnl.bash | 45 |
2 files changed, 46 insertions, 0 deletions
diff --git a/README.markdown b/README.markdown index 8d732936..e2a6c13c 100644 --- a/README.markdown +++ b/README.markdown @@ -175,6 +175,7 @@ There are a few other little tricks in `bash/bashrc.d`, including: * `bd` — Change into a named ancestor of the current directory * `ca` — Count given arguments * `cf` — Count files in a given directory +* `fnl` — Run a command and save its output and error into temporary files * `hgrep` — `HISTFILE` search * `mkcd` — Create a directory and change into it * `mkcp` — Create a directory and copy arguments into it 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" +} + |