【问题标题】:AppleScript: how to get the current directory of the topmost TerminalAppleScript:如何获取最顶层终端的当前目录
【发布时间】:2011-03-13 15:25:07
【问题描述】:

我想获取最顶层终端选项卡/窗口的当前目录(通过 AppleScript 或其他方式,这并不重要)。我该怎么做?

【问题讨论】:

    标签: terminal applescript working-directory


    【解决方案1】:

    另一种解决方案。

    get_foregroundterminal_curdir_fast.scpt:

    tell application "Terminal"
        do shell script "lsof -a -p `lsof -a -c bash -u $USER -d 0 -n | tail -n +2 | awk '{if($NF==\"" & (tty of front tab of front window) & "\"){print $2}}'` -d cwd -n | tail -n +2 | awk '{print $NF}'"
    end tell
    

    我使用lsof 本身来获取相应终端窗口的 bash shell 的 PID。这比使用fuser 快得多(毫秒与秒)。

    【讨论】:

      【解决方案2】:

      在发布有关如何在 Applescript 中查找当前目录的问题时,我被指出了该问题,因此我发布此答案是为了让未来被推荐的读者知道例外答案存在缺陷。

      如果当前目录路径中有一个SPACE字符,那么它只返回(最后一个)SPACE字符之后的路径部分!

      改用这个简单的脚本,它处理每个路径:tell application "Terminal" to set currentDirectory to (do shell script "pwd")

      【讨论】:

      • 不是说路径有空格。
      • @ppasler - 他说他想要“当前路径”。除非程序员也完全控制终端,否则用户可以轻松“cd”到路径中有空格的目录。
      【解决方案3】:

      好的,我有一个解决方案。

      get_foregroundterminal_proclist.scpt:

      tell application "Terminal"
          do shell script "fuser " & (tty of front tab of front window)
      end tell
      

      get_foregroundterminal_curdir.sh:

      #!/bin/bash
      
      function pwdx {
          lsof -a -p $1 -d cwd -n | tail -1 | awk '{print $NF}'
      }
      
      for pid in $(osascript "$(dirname "$0")/get_foregroundterminal_proclist.scpt"); do
          pwdx $pid
          break # break on first
      done
      

      【讨论】:

        猜你喜欢
        • 2020-06-10
        • 1970-01-01
        • 2010-10-26
        • 2017-10-26
        • 2013-06-26
        • 1970-01-01
        • 2012-07-01
        • 2015-01-28
        相关资源
        最近更新 更多