4
A
回答
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語句只是比較祖父進程名稱和一些已知的終端仿真程序。
相關問題
- 1. 如何判斷AsyncTaskLoader運行
- 2. 如何判斷用戶在NSTextView中選擇文本的時間
- 3. 如何在bash終端中選擇行
- 4. 如何判斷用戶是否選擇不安裝插件?
- 5. 如何判斷我的客戶端是否正在運行安全連接(SSL)
- 6. 如何判斷CheckBoxList的檢查/選擇 -
- 7. 如何判斷終端使用哪個版本的Ruby?
- 8. 如何運行終端
- 9. 如何判斷用戶是否在我的頁面上選擇了文本
- 10. 在iOS 10的MSStickerBrowserViewController中,如何判斷用戶選擇了哪個貼圖?
- 11. 如何判斷RandomizedSearchCV從發佈或無值中進行選擇?
- 12. 如何判斷STDIN是否連接到Perl的終端?
- 13. 如何在Ubuntu中運行PyCharm - 「運行在終端」或「運行」?
- 14. 如何判斷用戶使用jQuery
- 15. 永久禁用'運行終端'選項
- 16. WScript.Shell始終運行在頂端選項
- 17. 如何讓用戶選擇終端(Ruby)中的網格位置?
- 18. 如何判斷openoffice的哪個應用程序正在運行?
- 19. 如何判斷H2O 3.11.0.266是否在使用GPU運行?
- 20. 應用程序如何判斷它是否在hackintosh上運行?
- 21. 如何判斷應用程序在C++中運行的位置
- 22. 如何判斷全屏應用程序是否正在運行?
- 23. 如何用QProcess運行vim終端
- 24. 如何運行在不同的終端
- 25. 如何在mac終端上運行adb?
- 26. Linux和終端:如何在終端預約中運行命令?
- 27. 如何判斷用戶來自哪裏?
- 28. 如何判斷用戶的狀態?
- 29. Rails選擇查詢別名 - 如何判斷它是否可用?
- 30. 選擇選項錯誤,但在客戶端上運行