How can I switch to an open tab in Safari using osascript?
It's System Events that handles the keystrokes.

In normal AppleScript the code would look like:

tell application "Safari"
    activate
    delay 0.5
    tell application "System Events"
        key code 19 using command down
    end tell
end tell


As an osascript command line, it would be:

osascript -e 'tell application "Safari" to activate' -e 'delay 0.5' -e 'tell application "System Events" to key code 19 using command down'


The osascript command line from above shown below as multiple lines for clarity:

osascript -e 'tell application "Safari" to activate' \
          -e 'delay 0.5' \
          -e 'tell application "System Events" to key code 19 using command down'


Notes: Before telling System Events to keystroke, the target of the keystroke must have focus. So first, Safari must be made the frontmost window with activate. You must then allow a moment for it to have focus before the keypress and that is done with delay 0.5 and the value of delay may need to be adjusted in seconds and or decimal fractions thereof. So once Safari is the frontmost window, then System Events can issue the keystrokes.

This of course assumes Safari is already open with at least one window having two tabs!

The keystroke used herein with Safari is a Safari 9 (El Capitan) keyboard shortcut as shown in: Safari 9 (El Capitan): Safari keyboard and other shortcuts


  Select one of your first nine tabs &nbsp;&nbsp;&nbsp;&nbsp; Command-1 to Command-9