Alexander Mills
Alexander Mills

Reputation: 99960

Exit if in a script, do not exit if using a terminal/tty

If the user is entering commands in a terminal, I want to echo an error statement, but I do not want the terminal to close, so I have this:

  if [[ "$fle" =~ [^a-zA-Z0-9] ]]; then
    echo "quicklock: lockname has invalid chars - must be alpha-numeric chars only."
    if [[ -t 1 ]]; then
        # if we are in a terminal just return, do not exit.
        return 1;
    else
        exit 1;
    fi
  fi

however the if [[ -t 1 ]]; then does not seem to work, the terminal window I am using just closes immediately, so I think exit 1 is being called.

Upvotes: 1

Views: 2464

Answers (2)

Alexander Mills
Alexander Mills

Reputation: 99960

This is actually what ended up working for me:

function on_conditional_exit {

   if [[ $- == *i* ]]; then
       # if we are in a terminal just return, do not exit.
      echo -e "quicklock: since we are in a terminal, not exiting.";
      return 0;
   fi

   echo -e "quicklock: since we are not in a terminal, we are exiting...";
   exit 1;

}

the test is to see if we are in terminal or in a script somewhere...if we are interactive, we are in a terminal..

Upvotes: 2

Inian
Inian

Reputation: 85530

The -t flag checks if any of the standard file descriptors are open, and specifically [ -t 1 ] will represent if the STDOUT is attached to tty, so when running from the terminal, it will always assert this condition as true.

Also the return keyword is applicable only when running a function to break out of it instead of terminating the shell itself. Your claim of terminal window closing because of hitting exit 1 when running from script, could happen only if you source the script, (i.e. in the same shell) and will not happen if you execute the script in a sub-shell.

You can use a construct for a no-action in scripts by just doing : in the if condition as

if [[ -t 1 ]]; then
    # if we are in a terminal just return, do not exit.
    :

Also -t is defined by POSIX because of which you can do just [ -t 1 ].

Upvotes: 3

Related Questions