Search code examples
bashfirefoxunixprocesskill

Opening and closing a process using bash


Using Ubuntu, I would like to create a shell script (bash) for an Ubuntu server, that will open an instance of firefox and then close that specific instance the browser?

To open an instance of firefox, I can write:

firefox www.example.com

I have read that to search for all firefox instances, and to close them manually I can write:

ps aux | grep firefox
pidof firefox
kill #process#

But is there a way for me to search for the specific instance instance of firefox that I opened at the start?


Solution

  • You can use jobs to get the IDs of all running processes started from that shell (e.g. inside your script)

    #!/bin/bash
    
    firefox www.example.com &
    PID=$(jobs -p)
    
    kill $PID
    

    See help jobs for the options. Note that jobs lists all process started from this shell, so if you follow this approach and want to kill multiple processes you might need to do some additional parsing on the output from jobs to find the correct process.