Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MacOS Script to Open Terminal with Multiple Tabs

I need to create a small macos script file that would automatically open a terminal with 3 tabs. Each tab should point at a different location and then run a certain command, without ending the process after that.

As an example, let's say I want to open a terminal window with 3 tabs pointing to the Downloads, Desktop and Documents folders. Each of them would them perform the ls command and then wait for further commands.

Screenshot

Any idea how to do that?

like image 338
Andrei Statescu Avatar asked Oct 19 '25 15:10

Andrei Statescu


1 Answers

This may be an older question, but it's still valid. To answer your specific question, executing commands in multiple Terminal tabs on a Mac; You can use AppleScript for automating the Mac's UI. Below I've written an example Bash script that wraps AppleScript, to send commands to Terminal:

#!/usr/bin/env bash

DIR_NAME="$1"
COMMAND="$2"

osascript << EOF
tell application "Terminal"
    activate
end tell
tell application "System Events"
    keystroke "t" using command down
    set textToType to "cd ${DIR_NAME} && ${COMMAND}\n"
    keystroke textToType
end tell
EOF

It consumes two arguments, DIR_NAME (the folder to execute in) and the COMMAND you want to run as the second argument.

You can save this script to your Desktop, mark it as executable (chmod +x ~/Desktop/open_new_tabs.sh) and execute this script from your Terminal's command line.

To open multiple tabs, execute the script in a loop. In this example, I have a list of folders I'd like the command to run from, saved in a text file:

% cat ~/Desktop/list_of_dirs.txt
/tmp
/Applications
/
% for i in $(cat ~/Desktop/list_of_dirs.txt); do
  ~/Desktop/open_new_tabs.sh $i ls
done

Caveat with Mac OS Security: The first time you run this, you will be prompted if Terminal has permission to control System Events. If you don't see the prompt, you can add Terminal to your allowed apps: Systems Preferences > Security & Privacy > Accessibility > Privacy. Make sure there is a check next to Terminal.

Two alternatives:

  1. Use iTerm2 instead: Open all of your tabs, and cd into each dir you want to run the command in. Then use File > Broadcast to send your key stroke to all tabs.

  2. An alternative to multiple Terminal windows, would be to use multiple screen windows. This also works across platforms, which is nice.

like image 192
git_driver Avatar answered Oct 22 '25 03:10

git_driver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!