Shell Scripting – JOB SPEC & Command
Last Updated :
07 Nov, 2022
Prerequisites: Bash Scripting, Shell Function Library
Processes started from the terminal (and still not terminated) get a unique serial number or ID that is known as job spec or job ID. With the help of the job spec of a particular process, we can send signals to it or make that particular process run in the foreground or background. We can also list all the processes started from terminal and their current status from the jobs utility. The & symbol is used to run processes in the background. As foreground processes don’t allow the shell prompt in the terminal to return, there is a constant need for the & symbol to run processes in the background.
Syntax of ‘&’ symbol and its working
The & symbol is appended at the end to run processes in the background.
$ process_name &
$ /path/to/process_name &
$ process_name <args> &
For example, let us start some programs(processes) in the background using the & symbol :
Syntax and working of the Job spec
- Every process gets a unique job spec which is shown enclosed in square brackets [ ]
- A % symbol is prepended to the job spec when used in a command.
- With the help of job spec, one can send a signal to that particular process having that job spec or make it a foreground/background process.
- A job may also be referred to by % followed by the process name.
- The current job is referenced using %+ or %% while the previous job is by %-
Jobs and their respective job specs can be viewed from the command jobs.
$ jobs
$ jobs %jobSpec
$ jobs %processName
$ jobs %+ (or %%)
$ jobs %-
$ fg %jobSpec
$ bg %jobSpec
$ kill %jobSpec
Creating Shell Script
We will create a shell script that will launch the processes in the background with the help of & a symbol and then view its job spec.
The name of the script will be launch.sh
$ touch launch.sh
Make it an executable file.
$ chmod +x launch.sh
Open the file and add the following Script.
#!/bin/bash
# enabling job control in the script
set -m
# iterating the list of args which has process names
# and launching them in background
for process in $@ ; do
$process &
done
sleep 1;
# viewing the list of jobs and their job specs
echo "Jobs and their jobspecs are :"
jobs;
sleep 1;
echo
# killing the processes before the script ends
jobspec=1
while (( jobspec <= $# )) ; do
kill -SIGINT "%$jobspec"
echo "Job having jobspec $jobspec is terminated."
(( jobspec++ ))
done
exit 0
Run the Script
$ ./launch.sh <args> #args should be program(process) names
Share your thoughts in the comments
Please Login to comment...