Linux Script Control

内容概要: Handling Signals, Running Scripts in Background Mode, Job Control, Being Nice, Running Like Clokcwork, Start At the beginning.


1. Handling Signals:

1.1 Linux Signals Revisited

There are over 30 Linux signals that can be generated by the system and applicaitons.

Here are some commonly used signals:
Signal Value Description
1 SIGHUP Hang up the process
2 SIGINT Interrupt the process
3 SIGQUIT Stop the process
9 SIGKILL Unconditionly terminate the process
15 SIGTERM Terminate the process if possible
17 SIGTOP Unconditionally stop, but don’t terminate the process
18 SIGSTP Stop or pause the process, but don’t terminate
19 SIGCONT Continue a stopped process
1.2 Generating signals
KEY Signal
Ctrl-C SIGINT
Ctrl-Z SIGSTP
1.3 Trapping signals

The trap command allows you to specify which linux signals your shell script can watch for and interrupt from the shell.
trap commands signals

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
trap "echo haha!" SIGINT SIGTSTP SIGTERM
echo "This is a test program!"
count=1
while [ $count -le 10 ]
do
echo "LOOP#$count"
sleep 10
count=$[$count+1]
done
echo "The End"

Another example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
trap "echo byebye" EXIT

count=1
while [ $count -le 10 ]
do
echo "LOOP#$count"
sleep 4
count=$[$count+1]
done
echo "The End"

# Remove the trap
#trap - EXIT
#echo "Goodbye without trapping"


2. Running scripts in Background Mode

2.1 Running in the background

&

1
$ bash script &

2.2 Running script without a console

nohup
start a shell script from a terminal session, then let it run in background mode until it finishes, even if you exit the terminal session.

1
$ nohup ./command &

3. Job Control

3.1 Viewing jobs

jobs

3.2 Restarting jobs
  • To restart a job in background mode : bg
  • To restart a job in foreground mode : fg

4. Being nice

The scheduling priority is an integer value, from -20(highest) to +20(lowest) and default value is 0.
use nice command to change the priority:

  • nice : allows you to set the scheduling priority of a command as you start it.
  • renice : change the priority of a command that is aready running on the system.

5. Running Like Clockwork:

To run a script at a preselected time

  • at
  • batch
  • cron table

6. Start At the Beginning

Each user’s home directory contains two files that the bash shell uses to automatically start scripts and set environment variables:
  • .profile(or .bash-profile)
  • .bashrc
    6.1 Start a script at boot : .profile
    Place any scripts that you want run at login time in this file
    6.2 Start with a new shell : .bachrc
    The bash shell executes the script every time any user on the system starts a new bash shell.
    Append the following statement to the .bashrc
    1
    2
    3
    4
    5
    ...
    ...
    ...

    echo "Hello, this statement will be echoed each time when you lunch a shell!!!!!"