2

I have a script that starts firefox for 4 seconds, then kills it. Firefox will automatically log into a captive portal, so I only need it to be open for 4 seconds, as soon as the wifi connects. I am on Ubuntu 13.04.

My problem seems to be that $pid isn't set.

firefox ; pid=$!
sleep 4
kill $pid

EDIT: removed set, and now it gives kill an invalid pid.

5 Answers5

9

Your script does not work, because it waits until the firefox process has ended and afterwards executes pid=$!and the other command.

An easy way to do what you want is timeout:

timeout 4s firefox

It starts the program provided after the first argument and stops it after the time given as the first argument has passed.

Tim
  • 2,202
1

The reason your pid=$! fails is that $! is the PID of last job run in background.

I.e.,

$ foo & echo $!

will start foo and echo the PID of its process.

In your case, firefox ; pid=$! would need to be replaced with firefox & pid=$! but it might be pretty useless because firefox is a script which execs the actual binary.

What you need to do is either use killall (which will try to kill all the instances firefox, whether yours or other users') or (copy and) edit the /usr/bin/firefox script to echo the new PID.

sds
  • 2,108
0

A few more solutions.

Hennes
  • 65,804
  • 7
  • 115
  • 169
-1

After following a few hints from the other answers, I came up with this messy script:

firefox -no-remote -p c-portal &
ffpid=`ps aux | grep firefox | sed '2q;d' | tr -s ' ' | cut -d ' ' -f 2`
echo "firefox pid: $ffpid"
sleep 4
kill $ffpid

I also needed to go into about:config and change browser.sessionstore.resume_from_crash to false.

Explanation of each command: ps aux gets the full list of processes on the system, grep finds all the ones containing firefox, sed gets the second line (which appears to always be the latest instance of firefox), tr removes the extra spaces, cut gets the second column (-d means delimiter, which is a space).

After that string-processing mess, there's a debug thing that prints out the PID of firefox, sleep for 4 seconds, so it can log in, then it kills firefox. The about:config setting prevents it from trying to restore the session.

-2

I'm not sure if it fits your situation, but you could use killall instead of kill. So it would be:

firefox
sleep 4
killall firefox

I think a more correct approach is to get the last firefox process using ps aux | grep firefox, but today I don't know how to do that treatment of returning only that highest process number using bash script.

Jesse
  • 107