TerminalCommander is an AppleScript library to help excuting shell commnads in Terminal.app. It is easy simple excution of shell commands in Terminal.app by using "do script" command. This libary provides following flexibily to control Terminal.app.
Basic scirpt using TerminalCommander has following sqeuence.
If following shell script (cwd-tty.sh) is appended into, ~/.bash_profile or ~/.zprofile, TerminalCommander can find a terminal window of specified working directory.
cwd-tty.sh records correspondance between tty device name and working directory into ~/.cwd-tty file, just before new prompt is displayed.
cwd-tty.sh is placed in the bundle of TerminalCommander. It is recommended to append follwing line into ~/.bash_profile or ~/.zprofile.
source '~/Library/Scripts Libraries/TerminalComannder.scpt/Contents/Resources/cwd-tty.sh'
# cwd-tty.sh # # script to mainten a correspondence table between ttyname and # working directory. # Insert following line into .zprofile or .bash_profile. # # source path-to-dir/cwd-tty.sh # # 2.0 -- 2020-01-09 # * Added support of zsh if [[ $TERM_PROGRAM = 'Apple_Terminal' ]] && [[ -z $INSIDE_EMACS ]]; then save_cwd() { local ttyname=`tty`; if [[ ! -e ~/.cwd-tty ]]; then echo "$ttyname $PWD" > ~/.cwd-tty return fi local out=() local matched=0 local LINE while read LINE ; do newline="${ttyname} ${PWD}" case $LINE in ${newline}) return;; ${ttyname}" "*) out+=("$newline") matched=1;; *) out+=("$LINE");; esac done < ~/.cwd-tty if [[ $matched -eq 0 ]]; then out+=("$ttyname $PWD") fi IFS=$'\n' echo "${out[*]}" > ~/.cwd-tty unset IFS } if [[ -n $ZSH_VERSION ]]; then autoload add-zsh-hook add-zsh-hook precmd save_cwd else PROMPT_COMMAND="save_cwd${PROMPT_COMMAND:+; $PROMPT_COMMAND}" fi fi
Set a target woking directory into the instance with set_working_directory to find a terminal by working directory. The instance find a tty devie corresponding specfied working directory from ~/.cwd-tty file.
If an intended terminal widow is not found, shell commands will be executed in a new terminal. It is recommend to set cd command with set_execution_string which is shell commands executed at the beginning of a new terminal.
In the following sample, shell commands are sent to Terminal.app in three times. When the third command is sent, a working directory which is same to directory of the first terminal is specified. Pay attention the third command will be sent to the first terminal.