Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting interactive shell within ksh ENV script

Tags:

shell

unix

ksh

What's the preferred way to determine if a given ksh invocation is running an interactive shell?

I have some commands in an ENV file that I would like to skip for non-interactive ksh invocations (e.g. when executing a shell script).

I've seen suggesting ranging from:

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

...to not even sourcing .kshrc unless the shell is determined to be interactive using this cryptic incantation:

ENVIRON=$HOME/.kshrc                                    export ENVIRON
ENV='${ENVIRON[(_$-=1)+(_=0)-(_$-!=_${-%%*i*})]}'       export ENV
like image 285
David Citron Avatar asked Jun 03 '09 15:06

David Citron


People also ask

How do I know if I have an interactive shell?

If a script needs to test whether it is running in an interactive shell, it is simply a matter of finding whether the prompt variable, $PS1 is set. (If the user is being prompted for input, then the script needs to display a prompt.) Alternatively, the script can test for the presence of option "i" in the $- flag.

What is interactive shell script?

An interactive shell is defined as the shell that simply takes commands as input on tty from the user and acknowledges the output to the user. This shell also reads startup files that occurred during activation and displays a prompt.


2 Answers

I have found checking the $- variable for the 'i' flag the best method in ksh.

if [[ $- = *i* ]]; then
    #do interactive stuff     
fi
like image 150
Clinton Avatar answered Sep 29 '22 12:09

Clinton


In bash, these two methods are often used inside ~/.bashrc:

  • Check if stdin is a tty:

    [ -t 0 ] || return
    

    or

    if [ -t 0 ]; then
        # do interactive stuff
    fi
    
  • Check if the prompt ($PS1) is set:

    [ -z "$PS1" ] || return
    

But I don't know how to do that in ksh.

like image 40
user1686 Avatar answered Sep 29 '22 12:09

user1686