Last active
January 28, 2026 20:25
-
-
Save linux4life798/57e932a26edbd9398332ba153111a662 to your computer and use it in GitHub Desktop.
My bash msg-run function, but self contained for easy copy/paste. The full version can be found https://github.com/linux4life798/bash-includes/blob/main/bash_include.d/1-msg-print.bash .
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://github.com/linux4life798/bash-includes/blob/main/bash_include.d/1-msg-print.bash | |
| # Print command before running it. | |
| # Usage: msg-run [cmd] [args...] | |
| # | |
| # Example: msg-run sudo apt install -y vim | |
| msg-run() { | |
| local f="" redir="" | |
| # Use $$ and /proc because we subshell this check, thus we need parent PID and can't use /dev/fd. | |
| for f in " <$(readlink /proc/$$/fd/0)" " >$(readlink /proc/$$/fd/1)" " 2>$(readlink /proc/$$/fd/2)"; do | |
| redir+="${f##*/dev/pts/*}" | |
| done | |
| redir="${redir//$PWD\//}" | |
| printf "\E[34m%s\E[m\n" "> $*${redir}" >&2 | |
| "$@" | |
| # Show returned value only on error: | |
| #local r=$?; [ $r -ne 0 ] && printf '\E[31mReturned %d\e[m\n' $r >&2; return $r | |
| # Always show returned value: | |
| #local r=$?; printf '\E[%smReturned %d\e[m\n' $((r?31:33)) $r >&2; return $r | |
| } | |
| ###### OSX Compatibility ###### | |
| msg-run() { | |
| local f="" t="" redir="" | |
| for f in " <:0" " >:1" " 2>:2"; do | |
| t=$(lsof -wad${f##*:} -Fn -p$$ | sed -n 's/^n//p') | |
| [[ $t == /dev/pts/* || $t == /dev/tty* ]] || redir+="${f%:*}$t" | |
| done | |
| redir="${redir//$PWD\//}" | |
| printf "\E[34m%s\E[m\n" "> $*${redir}" >&2 | |
| "$@" | |
| # Show returned value only on error: | |
| #local r=$?; [ $r -ne 0 ] && printf '\E[31mReturned %d\e[m\n' $r >&2; return $r | |
| # Always show returned value: | |
| #local r=$?; printf '\E[%smReturned %d\e[m\n' $((r?31:33)) $r >&2; return $r | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment