我想在我的代碼中有一個部分,當輸出在終端中列印時才執行,而不是通過管道或重定向到文本檔案或其他程式中。
我試過這個:
#!/bin/bash
if [[ $(tty "-s") ]]; then
printf "You are using a terminal.\n"
else
printf "You are not using a terminal.\n"
fi
tty -s && printf "Guten Tag.\n"
./tty.sh命令后輸出:
You are not using a terminal.
Guten Tag.
`./tty.sh > test.txt` 后在 test.txt 中輸出:
``` 你沒有使用終端。古騰標簽。``
uj5u.com熱心網友回復:
請記住,bash 中的 if 陳述句會檢查所提供命令的退出狀態:
if command; then
# then block
else
# else block
fi
并且[[只是一個特殊的內置命令。
只需使用:
if tty -s; then
在tty -s退出狀態為 0 的情況下運行一些代碼,(成功)
并且不要使用tty來檢查輸入是否為終端,[ -t 0 ]而是使用。
if [ -t 0 ]; then
見man 1 tty和man 1 test。
如果從 中不清楚man 1 test,那么您可以分別測驗標準輸出和標準錯誤輸出是否是終端:
[ -t 1 ] # stdout is a terminal
[ -t 2 ] # stderr is a terminal
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/383847.html
上一篇:自定義bash提示PS1
