2010-08-05 62 views

回答

6

嚴格地說,你不能告訴用戶是否選擇點擊腳本後點擊「運行終端」,或者啓動終端並從那裏運行腳本。但下面的命令應該會對你有所幫助,特別是[ -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 
0

從來沒有嘗試過,但可能這個工程:

if [ -t 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 

現在,讓我稍微詳細地解釋一下。在終端執行腳本的情況下,其父進程始終是一個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語句只是比較祖父進程名稱和一些已知的終端仿真程序。

相關問題