0

I am trying to write a script which will two tabs on a terminal. I want each tab to tail a different logfile. The script is located in a /scripts directory and the logs are located in the parent directory.

The first tab and tail works fine. The second does not because it opens it in my home directory.

Here is the script:

CURRENT_DIR=$(pwd);

# First tail
osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' -e 'tell application "Terminal" to do script "cd ..;tail -f my.log" in selected tab of the front window';

# Second tail
cd $CURRENT_DIR;
osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' -e 'tell application "Terminal" to do script "cd ..;tail -f mySecond.log" in selected tab of the front window';

The second tail never works because it opens the tab in my home directory for some odd reason.
Usually when I do cmd + t the new terminal tab opens in the same directory.

Any ideas on what I am doing wrong?

Breako Breako
  • 6,353
  • 14
  • 40
  • 59

2 Answers2

2

I wouldn't rely on that behaviour. The "opening in the same directory" trick is dependent on the shell changing the title bar of the terminal window, which (a) doesn't always happen when you expect it to, and (b) breaks if a process other than the shell itself decides to modify the title bar.

I would err on the side of caution and pass a full path to the command in both cases, and use the on run mechanism to pass this path as a command line parameter (which is simpler and safer than trying to get the quoting right if the path might contain spaces):

osascript -e 'on run argv' \
          -e '  tell application "Terminal" to do script "cd " & quoted form of item 1 of argv & " ; tail -f ../mySecond.log" in selected tab of the front window' \
          -e 'end run' \
          "$CURRENT_DIR"

This means you don't care what the "current" directory is for that tab, the tail will always show you the right file.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
0

I did this by doing:

pwd=`pwd`
osascript -e "tell application \"Terminal\"" \
    -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
    -e "do script \"cd $pwd; tail -f my.log \" in front window" \
    -e "end tell"
    > /dev/null;

osascript -e "tell application \"Terminal\"" \
    -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
    -e "do script \"cd $pwd; tail -f mySecond.log\" in front window" \
    -e "end tell"
    > /dev/null;
Breako Breako
  • 6,353
  • 14
  • 40
  • 59
  • 1
    You should add some extra escaped quotes in case `$pwd` has spaces in it, it gets a bit messy but something like `-e "do script \"cd \\\"$pwd\\\"; tail -f mySecond.log\" in front window"` – Ian Roberts Oct 14 '13 at 18:14