【问题标题】:How to tell if user selected "Run In Terminal"如何判断用户是否选择了“在终端中运行”
【发布时间】:2011-03-25 23:11:33
【问题描述】:

当你双击一个 bash 脚本时,Ubuntu 会询问用户是否想要在终端中显示、运行或运行...

脚本中有没有办法确定用户是否选择了“在终端中运行”?

【问题讨论】:

    标签: linux bash ubuntu


    【解决方案1】:

    从未尝试过,但可能可行:

    if [ -t 1 ] ;
    

    虽然如果输出它也是错误的......

    【讨论】:

      【解决方案2】:

      严格来说,您无法判断用户是在单击脚本后选择“在终端中运行”,还是启动终端并从那里运行脚本。但是下面的命令应该对你有所帮助,尤其是[ -t 2 ]

      if [ -t 1 ]; then
        echo "Standard output is a terminal."
        echo "This means a terminal is available, and the user did not redirect the script's output."
      fi
      
      if [ -t 2 ]; then
        echo "Standard error is a terminal." >&2
        echo "If you're going to display things for the user's attention, standard error is normally the way to go." >&2
      fi
      
      if tty >/dev/null; then
        echo "Standard input is a terminal." >$(tty)
        echo "The tty command returns the name of the terminal device." >$(tty)
      fi
      
      echo "This message is going to the terminal if there is one." >/dev/tty
      echo "/dev/tty is a sort of alias for the active terminal." >/dev/tty
      if [ $? -ne 0 ]; then
        : # Well, there wasn't one.
      fi
      
      if [ -n "$DISPLAY" ]; then
        xmessage "A GUI is available."
      fi
      

      【讨论】:

        【解决方案3】:

        这是一个例子:

        #!/bin/bash
        
        GRAND_PARENT_PID=$(ps -ef | awk '{ print $2 " " $3 " " $8 }' | \
            grep -P "^$PPID " | awk '{ print $2 }')
        
        GRAND_PARENT_NAME=$(ps -ef | awk '{ print $2 " " $3 " " $8 }' \
            | grep -P "^$GRAND_PARENT_PID " | awk '{ print $3 }')
        
        case "$GRAND_PARENT_NAME" in
        gnome-terminal)
            echo "I was invoked by gnome-terminal"
            ;;
        xterm)
            echo "I was invoked by xterm"
            ;;
        *)
            echo "I was invoked by someone else"
        esac
        

        现在,让我更详细地解释一下。在(in)终端执行脚本的情况下,其父进程始终是shell本身。这是因为终端模拟器运行 shell 来调用脚本。所以这个想法是看一个祖父母过程。如果祖父进程是终端,那么您可以假设您的脚本是从终端调用的。否则,它会被其他东西调用,例如 Nautilus,它是 Ubuntu 的默认文件浏览器。

        以下命令为您提供父进程 ID。

        ps -ef | awk '{ print $2 " " $3 " " $8 }' | grep -P "^$PPID " | awk '{ print $2 }'
        

        这个命令给你一个你父母的父进程的名字。

        ps -ef | awk '{ print $2 " " $3 " " $8 }' | grep -P "^$GRAND_PARENT_PID " | awk '{ print $3 }'
        

        最后的 switch 语句只是将祖父进程名称与一些已知的终端仿真器进行比较。

        【讨论】:

          猜你喜欢
          • 2021-09-09
          • 2020-02-06
          • 2021-07-12
          • 2011-04-18
          • 1970-01-01
          • 2013-12-27
          • 2015-10-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多