Blog

03/06/2019

Bash Check If Shell Is Interactive or Not Under Linux / Unix Oses



How do I check in GNU/Bash if a shell is running in interactive mode or not while writing shell scripts?

A bash shell is considered as an interactive shell when it reads and writes data from a user’s terminal. Most startup scripts examine the shell variable called PS1. Usually, PS1 is set in interactive shells, and it is unset in non-interactive shells.

Find out if this shell interactive using PS1

The syntax is as follows:

// Is this Shell Interactive?
[ -z "$PS1" ] && echo "Noop" || echo "Yes"

OR


[ -z "$PS1" ] && echo "This shell is not interactive" || echo "This shell is interactive"

OR


[ -z "$PS1" ] && die "This script is not designed to run from $SHELL" 1 || do_interacive_shell_stuff

You can use bash shell if..else..fi syntax as follows:

if [ -z "$PS1" ]; then
       die "This script is not designed to run from $SHELL" 1
else
       //call our function
       do_interacive_shell_stuff
fi

From the bash reference manual

To determine within a startup script whether or not Bash is running interactively, test the value of the ‘-‘ special parameter. It contains i when the shell is interactive. For example:

case "$-" in
    *i*) echo "This shell is interactive" ;;
      *) echo "This shell is not interactive" ;;
esac

tty command

You can also use tty command as follows:

tty -s && echo "This shell is interactive" || echo "This shell is not interactive" ;;

OR

ssh user@server1.sxi.io tty -s && echo "This shell is interactive" || echo "This shell is not interactive" ;;
References:

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...