Skip to content

Instantly share code, notes, and snippets.

@tednaleid
Last active August 10, 2019 21:28
Show Gist options
  • Save tednaleid/0ecd1d39df807ba346a62356c504cc1a to your computer and use it in GitHub Desktop.
Save tednaleid/0ecd1d39df807ba346a62356c504cc1a to your computer and use it in GitHub Desktop.
wexec - shell function to allow easy iteration on a shell command, uses watchexec to re-run a command whenever the file is saved
# add to your .zshrc/.bashrc
# sets up "live reload"-like environment for for a single file
# will watch a file (create it if it doesn't exist), every time it is saved it will run a command
EDITOR=mvim # I use MacVim but switch this to whatever you use (something that'll be outside of the same terminal window)
function wexec() {
command -v watchexec >/dev/null 2>&1 || { echo "'watchexec' is required. e.g. brew install watchexec or cargo install watchexec" >&2; exit 1; }
if [[ -z $1 || "$1" == "--help" ]]; then
echo "usage: "
echo " wexec <file/command to watch>"
echo " the file will be assumed to be an executable command that will be run"
echo " when it changes"
echo ""
echo " ex: wexec foo.sh"
echo ""
echo " the file will be created and marked as executable if it does not exist"
echo "or:"
echo ""
echo " wexec <file/command to watch> <command args to run when file is changed>"
echo ""
echo " ex: wexec yolo.sql psql -f yolo.sql"
echo ""
return -1
fi
FILE=$1
if [[ -z $2 ]]; then
# if no further commands are passed, then the file is the command
COMMAND="./$FILE"
if [ ! -f $FILE ]; then
# create the file as it doesn't exist, make it executable as it is the command
touch "$FILE"
chmod +x "$FILE"
fi
else
if [ ! -f $FILE ]; then
# create the file as it doesn't exist, don't make it executable, it is not the command
touch "$FILE"
fi
# all the args after the first are the command to run
COMMAND="${@:2}"
fi
# open the file in an editor for changes
$EDITOR "$FILE"
bash -c "watchexec -s SIGINT -r -d 100 -f '*/$FILE' '$COMMAND'"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment