Skip to content

Instantly share code, notes, and snippets.

@dofy
Last active April 6, 2023 06:58
Show Gist options
  • Save dofy/6b0635e850cc39edb9606a8537b1a55d to your computer and use it in GitHub Desktop.
Save dofy/6b0635e850cc39edb9606a8537b1a55d to your computer and use it in GitHub Desktop.
Auto run any zsh/bash command in macOS Terminal when WD changed.
#!/bin/zsh
# any command e.g.
echo "auto run success..."
# save file to ~/.auto_run
# and
# chmod +x ~/.auto_run

Auto Run zsh/bash script when work direction be changed (macOS Terminal)

Warning

Now this Script has a New Version

More flexible, more convenient, simpler, and more free.

Usage

cd ~
touch .auto_run
chmod +x .auto_run
mkdir .zsh
touch .zsh/auto_run.zsh

copy auto_run.zsh content and paste clipboard content to your auto_run.zsh file and save it.

then add following script to your .zshrc (maybe at last line)

source ~/.zsh/auto_run.zsh
# == README ==
# source script below in ~/.zshrc
# and touch .auto_run in #HOME folder
# load zsh hook first
autoload -U add-zsh-hook
# == Script Begin ==
# auto_run script
auto_run() {
# auto run target root folder (you can change it)
AUTO_RUN_TARGET="$HOME/Works"
# auto run script (you can change it too OR NOT)
AUTO_RUN_SCRIPT="$HOME/.auto_run"
typeset -l auto_run_target="${AUTO_RUN_TARGET%/}"
typeset -l work_direction="${PWD%/}"
if [[ "$work_direction" == "$auto_run_target"* ]] then
# you can execute something first e.g.
# echo "copyright (C) 2023 powered by dofy.net"
# and execute the .auto_run script
if [ -f $AUTO_RUN_SCRIPT ] && [ -x $AUTO_RUN_SCRIPT ]; then
$AUTO_RUN_SCRIPT 2> /dev/null
fi
fi
}
# add function to zsh `chpwd` hook
add-zsh-hook chpwd auto_run
@dofy
Copy link
Author

dofy commented Apr 6, 2023

我现在主要是配合 devtodo 在使用, ~/.auto_run 中只有 todo 命令,这样可以在进入存在 .todo 文件夹的时候自动显示 todo list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment