Shell script to kill all background jobs

Discussion in 'Mac Programming' started by l0uismustdie, Nov 24, 2011.

  1. l0uismustdie macrumors regular

    l0uismustdie

    Joined:
    Nov 30, 2009
    Location:
    Edinburgh, UK
    #1
    Hello, I've come up with a command which will list all the background processes running in my current shell and am trying to run it from a shell script but am experiencing some difficulty. The script looks as follows:
    Code:
    #! /bin/sh                                                                      
    jobs -l | grep -o '[0-9]* ' | xargs -E eofstr kill -9
    
    If I run this line directly in my terminal it works fine but if I try to execute from the script it doesn't seem to do anything.

    Any ideas?

    Thanks.
     
  2. willieva macrumors 6502

    Joined:
    Mar 12, 2010
    #2
    The jobs command shows the processes that have been started in the current shell. When you run it in a script it is in a new shell and not aware of the jobs in the parent shell.
     
  3. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #3
    An alternative approach, create an alias instead of a script.
     
  4. l0uismustdie thread starter macrumors regular

    l0uismustdie

    Joined:
    Nov 30, 2009
    Location:
    Edinburgh, UK
    #4
    im not sure what you mean by 'create an alias'. And how could I use this to solve the problem. Thanks for responding!
     
  5. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #5
    As willieva mentioned, your script will run in a new shell. By creating an alias you can substitute the line you have with one identifier. Since this is just an alias, it will run in your current shell.

    Code:
    $ alias greetings='echo "hello"'
    $ greetings
    hello
    
     
  6. l0uismustdie thread starter macrumors regular

    l0uismustdie

    Joined:
    Nov 30, 2009
    Location:
    Edinburgh, UK

Share This Page