Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check isatty in bash

Tags:

bash

shell

I want my shell to detect if human behavior, then show the prompt.

So, assume the file name is test.bash

#!/bin/bash
if [ "x" != "${PS1:-x}" ] ;then
 read -p "remove test.log Yes/No" x
 [ "$x" = "n" ] && exit 1
fi
rm -f test.log

But, I found it can not work if I haven't set PS1. Is there better method?

my test methods:

./test.bash                  # human interactive
./test.bash > /tmp/test.log  # stdout in batch mode
ls | ./test.bash             # stdin in batch mode
like image 871
Daniel YC Lin Avatar asked Apr 05 '12 03:04

Daniel YC Lin


People also ask

What is $1 and $2 in bash?

$1 - The first argument sent to the script. $2 - The second argument sent to the script. $3 - The third argument... and so forth. $# - The number of arguments provided. $@ - A list of all arguments provided.

How do you check a variable in bash?

To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command.

What is $$ in bash script?

$@ - All the arguments supplied to the Bash script. $? - The exit status of the most recently run process. $$ - The process ID of the current script. $USER - The username of the user running the script. $HOSTNAME - The hostname of the machine the script is running on.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails. $@


2 Answers

to elaborate, I would try

 if [ -t 0 ] ; then
    # this shell has a std-input, so we're not in batch mode 
   .....
 else
    # we're in batch mode

    ....
 fi

I hope this helps.

like image 78
shellter Avatar answered Sep 23 '22 14:09

shellter


From help test:

 -t FD          True if FD is opened on a terminal.
like image 42
Ignacio Vazquez-Abrams Avatar answered Sep 25 '22 14:09

Ignacio Vazquez-Abrams