2

I am making a bash script for Linux which closes the terminal window if the window loses focus.

On the command line, I was able to do this:

termwin=$(xdotool getactivewindow)

while : 
do 
  if [[ $(xdotool getactivewindow) != $termwin ]]
  then 
    exit 
  fi 
done

It works typed manually into a terminal, but, if I put it into a script, instead of closing the window when focus is lost, the script simply stops. No error or anything, just back to a prompt.

I feel like I'm missing something basic.

EDIT

After reading this...: See here

I tried running this as ". test.sh" rather than "./test.sh" and it worked. The link describes the difference in these methods as running the script as a subprocess or as part of the main process, respectively. Can anyone just explain this, and/or modify the script to run successfully with "./" instead of ". ", in the latter creates issues?

2 Answers2

1

When you source the file with ., the commands will run just as if you had entered them in the command line. Thus exit will exit your currently running shell.

To exit the shell from which the script was executed when forking, you need to get the process id of the parent process. You can try running

kill ${PPID}

in the script instead of exit to kill the parent shell (tip: try just echoing the pid first and check which process it corresponds to so you don't kill your WM or something).

If ${PPID} doesn't do it for you, you can also try sending the pid as a parameter to the script, but it depends on how and where it's called.


You said you used urxtvd/urxvtc. With that combination, this script kills the terminal from which it was started:

#!/bin/sh
echo kill in 3
sleep 3
kill -1 ${PPID}

so you should be able to use kill -1 in this way to kill a single urxvtc instance.

Note that if you run this by sourcing, then the urxvtd instance will be $PPID for the currently running terminal, and all terminals will die. You don't want that.

0

Hope the script will work as needed:

#!/bin/sh

termwin=$(xdotool getactivewindow)
while : ; do
    [ $(xdotool getwindowfocus) = $termwin ] || kill -9 $PPID
done
Rony
  • 180
  • 4