如何判断用户是否选择了“在终端中运行”

时间:2010-08-05 18:03:29

标签: linux bash ubuntu

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

脚本中是否有办法确定用户是否选择了“Run In Terminal”?

3 个答案:

答案 0 :(得分:6)

严格地说,您无法判断用户在单击脚本后是否选择了“Run In Terminal”,或者启动终端并从那里运行脚本。但是下面的命令可以帮助您,尤其是[ -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

答案 1 :(得分:1)

以下是一个例子:

#!/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语句只是将祖父进程名称与一些已知的终端仿真器进行比较。

答案 2 :(得分:0)

从未尝试过,但可能是有效的:

if [ -t 1 ] ;

虽然输出它的输出也是假的......