Is it possible to open a Private Browser window in Safari using Terminal.app

bashsafariterminal

I'm trying to open a Private Browser window in Safari using Terminal. I could open Safari using open command and this way, open /Applications/Safari.app/Contents/MacOS/Safari but I couldn't open a Private Browser window.

Please suggest how to open a Private Browser window from the command line.

Best Answer

Note: This is only one possible method. It works by simulating the pressing of ShiftCmdN. You can also simulate the pressing of the menu item, but the script is longer.

Create a new file, and paste in these contents:

#!/usr/bin/osascript
tell application "Safari"
    activate
    delay 0.5
    tell application "System Events"
        keystroke "n" using {command down, shift down}
    end tell
end tell

Save it somewhere (here, I'll pretend it's called myscript).

In Terminal, find the file and make it executable:

chmod +x myscript

Simply run it to create a new private window in Safari

./myscript

If you want to be able to use this script regardless of your current working directory, create an alias OR move it to /usr/local/bin.

If you want an alias, use

alias myscript='/path/to/script/myscript

You can add this line to ~/.bashrc or ~/.bash_profile to automatically load this alias when you start Terminal.