Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

bash: test for an interactive shell 4

Status
Not open for further replies.

Ghodmode

Programmer
Feb 17, 2004
177
NZ
How do I test within a bash script for the presence of an interactive shell?

The most common answer for this question says either to test the value of $PS1 or test for "i" in the value of $-. However, this isn't working for me in bash even though I'm fairly certain that I've used the $PS1 technique with Korn shell in Solaris.

Code:
vince@home:~/dev/workspace/practice$ echo -e "PS1: $PS1\n\$-: $-\n\nsetup.sh:\n`cat test.sh`"
PS1: ${debian_chroot:+($debian_chroot)}\u@\h:\w\$
$-: himBH

setup.sh:
if [ -z "$PS1" ]
then
        echo "NOT INTERACTIVE"
else
        echo "INTERACTIVE: \"$PS1\""
fi

case "$-" in
        *i*) echo "INTERACTIVE: \"$-\"" ;;
        *) echo "NOT INTERACTIVE: \"$i\"" ;;
esac
vince@home:~/dev/workspace/practice$ ./test.sh
NOT INTERACTIVE
NOT INTERACTIVE: ""

Is there another way?

Thank you.

--
-- Ghodmode

Give a man a fish and he'll come back to buy more... Teach a man to fish and you're out of business.
 
Code:
# determine if there's a controlling tty for this run of the script.
# if there's none, it means we're running from 'cron'
if [ -t 0 ] ; then
   inputTERM=1
fi;
'man bash' yields the following under 'CONDITIONAL EXPRESSIONS':
Code:
       [b]-t fd[/b]  True if file descriptor fd is open and refers to a terminal.

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Nice one Vlad, I always used sth like

Code:
if tty -s
then
 INTERACTIVE=y
else
 INTERACTIVE=n
fi

...

if [ ${INTERACTIVE} = 'y' ]
then
 echo "confirm Y/n :\c"
 read confirm junk
else
 confirm=y
fi

case ${confirm} in
 y*|Y*)
  #do action
  ;;
 *)
  #user abort
  ;;
esac

HTH,

p5wizard
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top