2009-06-03 175 views
5

確定給定ksh調用是否運行交互式shell的首選方法是什麼?檢測ksh ENV腳本中的交互式shell

我在ENV文件中有一些命令,我​​想跳過非交互式ksh調用(例如執行shell腳本時)。

我見過的提示爲from

if [[ $- = *i* ]]; then 
    # do interactive stuff 
fi 

...不,甚至採購.kshrc除非shell決心採用這種神祕incantation是互動:

ENVIRON=$HOME/.kshrc         export ENVIRON 
ENV='${ENVIRON[(_$-=1)+(_=0)-(_$-!=_${-%%*i*})]}'  export ENV 

回答

2

慶典,這兩種方法經常用在~/.bashrc裏面:

  • 檢查stdin是一個tty:

    [ -t 0 ] || return 
    

    if [ -t 0 ]; then 
        # do interactive stuff 
    fi 
    
  • 檢查提示($PS1)設定:

    [ -z "$PS1" ] || return 
    

但我不知道該怎麼辦在ksh中。

+0

'-t N'測試也在Korn shell中工作。 – 2009-06-03 15:48:28

4

我發現檢查' - '的$ - 變量標誌着ksh中最好的方法。

if [[ $- = *i* ]]; then 
    #do interactive stuff  
fi 
0

它也可以使用 'TTY -s':運行一個腳本時

The following exit values are returned: 

    0  Standard input is a terminal. 

    1  Standard input is not a terminal. 
0

一個適當的KSH外殼不應以$ ENV。然而,這在Sun的ksh88方言中是一個長期存在的bug,並且實際上在Solaris 10中進行了修補。(令人驚訝的是,由於Sun傳統上不願意改變現有行爲,因爲這樣的修復可能會破壞解決方法,在這種情況下,標準佔上風。)

爲防止sun的ksh88在運行腳本時讀取$ ENV,通常使用#!/bin/ksh -p解決方法,並且如果您沒有掛起/etc/suid_profile,則是安全的。

但是,$ - 交互式shell的可靠指標,除非您僞造它。

$ cat interactive.sh 
echo \$- = $- 
[[ $- == *i* ]] && echo interactive || echo not interactive 

當作爲一個腳本來運行這給:

$ ksh interactive.sh 
$- = hB 
not interactive 

當我們假的-i標誌,你會得到什麼,你問:

$ ksh -i interactive.sh 
$- = imBE 
interactive 

而且從交互shell來源時,它會做正確的事情:

$ . ./interactive.sh 
$- = imsBEl 
interactive