Created
August 25, 2021 00:16
-
-
Save alexmipego/89c59a5e3abe34faeaee0b07b23b56eb to your computer and use it in GitHub Desktop.
f-bind — ZSH auto run command
This file contains 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
#!/bin/zsh | |
# Explanation | |
# I've my mac setup so pressing F13-F19 will touch a file like ~/scripts/global-f13.watch. | |
# If I now run a command, say "make", and afterwards I run ". f-bind 13", then upon | |
# pressing F-13, the shell with automatically queue a "make" + <ENTER>. | |
# This preserves history, allows me to use a single shell, and doesn't interrupt | |
# other processes (say "man ls" for example). | |
if [[ $ZSH_EVAL_CONTEXT == 'toplevel' ]]; then | |
echo "Not sourced, run '. ${0##*/} $@' instead." | |
exit 1 | |
fi | |
if [ "$#" -ne 1 ]; then | |
echo "F Key number is required, try '. ${0##*/} 13' for F-13." | |
return | |
fi | |
# Get previous command | |
CMD=$(history -n | tail -n1) | |
ZSH_PID=$$ | |
BIND_TMP=`mktemp` | |
# Cleanup temp on exit | |
trap '{ rm -f -- "$BIND_TMP"; }' EXIT | |
function queue_cmd() { | |
# Fill the ZSH input buffer | |
print -z ${1} | |
# Send a new line to ZSH, excuting the command | |
# For some reason, leaving the command running as a bg job, requires two calls | |
python -c "import fcntl, sys, termios; fcntl.ioctl(sys.stdin, termios.TIOCSTI, '\n'); fcntl.ioctl(sys.stdin, termios.TIOCSTI, '\n');" | |
} | |
function usr2_handler() { | |
CMD=$(<${BIND_TMP}) | |
queue_cmd ${CMD} | |
} | |
trap usr2_handler USR2 | |
echo "Bound F-${1} to: ${CMD}" | |
fswatch -0 -o ~/scripts/global-f${1}.watch | xargs -0 -n1 -I{} zsh -c "echo '${CMD}' > ${BIND_TMP}; kill -s SIGUSR2 $$" & |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment