Add the following line to your ~/.zshrc
file. (Or, your ~/.bashrc
file, if you are using bash.) If the file does not exist, then create the file.
openwin() { osascript -e "tell application \"$1\" to activate" -e 'tell application "System Events" to keystroke "n" using command down'; }
The next time you open a Terminal window, you will be able to use the above function to send the key combination ⌘+N to the application specified. For example, to open a new window in Firefox, enter the following.
openwin firefox
For Microsoft Edge, enter either of the following.
openwin "microsoft edge"
openwin microsoft\ edge
The key combination ⌘+N is the default in most applications to open a new window.
When the above function is first used, you may need to do the following.
- Authorize the Terminal application to send Apple events to System Events. This can be found under Automation on the Privacy tab of the Security & Privacy pane of the System Preferences application.
- Allow
osascript
to send keystrokes. This is authorized by add the Terminal
application to Accessibility on the Privacy tab of the Security & Privacy pane of the System Preferences application.
An alternative to using a function would be to install a script. This would have the advantage of being customizable. Below is an example script which is named openwin
.
#!/bin/zsh
pgrep -i -x -q -U $UID "$1"
result=$? # If application is running then result will equal 0.
script=()
case ${1:l} in
mail)
script+=(-e "tell application \"$1\" to activate")
if [[ result -eq 0 ]]; then
script+=(-e 'tell application "System Events" to keystroke "n" using {command down, option down}')
fi;;
"microsoft word")
script+=(-e "tell application \"$1\" to activate")
script+=(-e 'tell application "System Events" to keystroke "n" using command down');;
*)
script+=(-e "tell application \"$1\" to activate")
if [[ result -eq 0 ]]; then
script+=(-e 'tell application "System Events" to keystroke "n" using command down')
fi
esac
if [[ $#script -ne 0 ]]; then
#printf "%s '%s'\n" $script # <-- Just for debugging.
osascript $script
fi
Below are the commands to install the script. Here I assume /usr/local/bin
is already in your PATH
variable.
sudo mkdir -p /usr/local/bin
sudo cp openwin /usr/local/bin
sudo chown root:wheel /usr/local/bin/openwin
sudo chmod a+x /usr/local/bin/openwin
The default for the example script is to activate the application, then send the ⌘+N key combination only if the application is already running.
The example script has the following customizations.
- For the Mail application, the ⌘+alt+N key combination is sent instead of the default ⌘+N.
- For the Microsoft Word application, the ⌘+N key combination is sent regardless of whether the application is running.
References