Professional Documents
Culture Documents
If we are using any major operating system, we are indirectly interacting with
the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are
interacting with the shell by using the terminal.
The shell can be defined as a command interpreter within an operating system like
Linux/GNU or Unix. It is a program that runs other programs. The shell facilitates
every user of the computer as an interface to the Unix/GNU Linux system. Hence,
the user can execute different tools/utilities or commands with a few input data.
The shell sends the result to the user over the screen when it has completed running
a program which is the common output device. That's why it is known as "command
interpreter".
The shell is not just a command interpreter. Also, the shell is a programming
language with complete constructs of a programming language such as functions,
variables, loops, conditional execution, and many others.
Graphical Shells
These shells specifies the manipulation of programs that are based on the graphical
user interface (GUI) by permitting for operations like moving, closing,
resizing, and opening windows and switching focus among windows as well. Ubuntu
OS or Windows OS could be examined as a good example that offers a graphical user
interface to the user to interact with the program. Various users don't need for
typing in any command for all the actions.
Command-line Shell
Various shells could be accessed with the help of a command-line interface by users.
A unique program known as Command prompt in Windows or Terminal in
macOS/Linux is offered for typing in the human-understandable commands like "ls",
"cat", etc and after that, it is being run. The result is further shown to the user on
the terminal.
Working on a command-line shell is a complicated for many beginners due to it is
hard to remember several commands. Command-line shell is very dominant and it
permits users for storing commands in a file and run them together. In this way, a
repetitive action could be automated easily. Usually, these files are known as Shell
scripts in macOS/Linux systems and batch files in Windows.
There are various types of shells which are discussed as follows:
Bash Shell
In the bash shell, bash means Bourne Again Shell. It is a default shell over several
distributions of Linux today. It is a sh-compatible shell. It could be installed over
Windows OS. It facilitates practical improvements on sh for interactive and
programming use which contains:
o Job Control
o Command-line editing
o Shell Aliases and Functions
o Unlimited size command history
o Integer arithmetic in a base from 2-64
Csh/Tcsh Shell
Tcsh is an upgraded C shell. This shell can be used as a shell script command
processor and interactive login shell.
Tcsh shell includes the following characteristics:
o C like syntax
o Filename completion and programmable word
o Command-line editor
o Job control
o Spelling correction
Ksh Shell
Ksh means for Korn shell. It was developed and designed by David G. Korn. Ksh shell
is a high-level, powerful, and complete programming language and it is a reciprocal
command language as well just like various other GNU/Unix Linux shells. The usage
and syntax of the C shell are very same as the C programming language.
All these shells do a similar job but take different commands and facilitate distinct
built-in functions.
The extension of the Korn shell The extension of the bash shell
1.
is .ksh. is .sh.
In the Korn shell, we use the print In Bash shell, we use the command
2.
command for printing any output. name echo printing any output.
The Korn shell can be found in We can find the bash shell in
3.
/bin/ksh. /bin/bash.
Developed by David Korn in the Developed by Brian Fox for the GNU
7.
early 1980s Project in the late 1980s
1
Generally faster than Bash Generally slower than Korn Shell
5
Shell Prompt
It is known as a command prompt and it is issued via the shell. We can type
any command while the prompt is shown.
Shell reads our input after we click Enter. It illustrates the command we want to be
run by seeing at the initial word of our input. A word can be defined as the
character's unbroken set. Tabs and spaces separate words.
The below is a common data command example that shows the current time and
date:
We can also customize our command prompt with the help of PS1 (environment
variable).
Shell Scripting
The common concept of the shell script is the command list. A good shell script will
contain comments which are preceded via # simbol.
Shell functions and scripts are interpreted. It means they aren't compiled.
There are also conditional tests like value Y is greater than value Z, loops permitting
us to proceed by massive data amounts, files to store and read data, and variables
to store and read data, and these scripts may contain functions.
The shells are usually interactive which means they receive commands as input
through the users and run them. Although sometimes we routinely wish to run a set
of commands, hence, we have to type within the commands all-time inside the
terminal.
A shell script includes syntax similarly to other programming languages. When we
have prior experience along with a programming language such as C/C++, Python,
etc. It will be very easy to begin with it. The shell script combines the below
components:
Functions
o Control flow: if, else, then, shell loops, case, etc.
o Shell commands: touch, pwd, echo, ls, cd, etc.
o Shell keywords: break, if, else, etc.
Shell Scripts Need
There are several causes to write these shell scripts:
o For avoiding automation and repetitive work
o Shell scripting is used by system admins for many routine backups
o Including new functionalities to the shell
o System monitoring etc.
Shell Script Advantages
o The syntax and command are exactly similar to those entered directly in a
command line. Thus, the programmers don't have to switch to completely
different syntax
o Interactive debugging
o Quick start
o It is much quicker to write the shell scripts etc.
Shell Script Disadvantages
o A single error can modify the command which could be harmful, so prone to
very costly errors.
o Design flaws in the language implementation and syntax.
o Slower execution speed.
o Offer minimal data structure dissimilar other scripting languages.
o Not well suited for complex and large tasks etc.
Script Example
Assume we make a test.sh script. We have to alert a system that the shell script is
started before we include anything else in our script.
Note: Every script will have a .sh extension.
It can be done with the help of the shebang construct.
For example:
1. #!/bin/sh
It shows the system that several commands that pursue are to be run by the Bourne
shell. It is known as the shebang due to the symbol # is known as hash and the
symbol ! It is known as the bang.
To make a script including these commands, we put the shebang construct line first,
and after that add any command:
1. #!/bin/bash
2. pwd
3. Is
Comments in shell
We can put our comments in our script below:
1. #!/bin/bash
Make the script runnable and save the content mention above:
1. $chmod +x test.sh
Now, the shell script is ready to be run:
1. $./test.sh
Under execution, we will get the result as follows:
1. /home/amrood
2. index.htm unix-basic_utilities.htm unix-directories.htm
3. test.sh unix-communication.htm unix-environment.htm
Note:- For executing a program present in the latest directory, we can use the
./program_name
# read-only variables
var_blood_group="O-"
readonly var_blood_group
echo "Blood group is $var_blood_group and read only."
echo "Error for read only variables, if trying to \
modify them."
echo
var_blood_group="B+"
echo
# unsetting variables
unset Var_age
echo "After unsetting var_age..."
echo
echo "Name is $Var_name, blood group is $var_blood_group\
and age is $Var_age..."
Output:
All outputs
Variable Types
We can discuss three main types of variables:
1) Local Variable:
Variables which are specific to the current instance of shell. They are basically used
within the shell, but not available for the program or other shells that are started
from within the current shell.
For example:
`name=Jayesh`
In this case the local variable is (name) with the value of Jayesh. Local variables is
temporary storage of data within a shell script.
2) Environment Variable:
These variables are commonly used to configure the behavior script and programs
that are run by shell. Environment variables are only created once, after which they
can be used by any user.
For example:
`export PATH=/usr/local/bin:$PATH` would add `/usr/local/bin` to the beginning of
the shell’s search path for executable programs.
3) Shell Variables:
Variables that are set by shell itself and help shell to work with functions correctly. It
contains both, which means it has both, some variables are Environment variable,
and some are Local Variables.
For example:
`$PWD` = Stores working directory
`$HOME` = Stores user’s home directory
`$SHELL` = Stores the path to the shell program that is being used.
Few more examples in Shell Scripting and Shell Variable
How to Store User Data in a Variable?
#!/bin/bash
echo "Enter the length of the rectangle"
read length
echo "Enter the width of the rectangle"
read width
area=$((length * width))
echo "The are of the rectangle is: $area"
In this example the variables ‘length’, ‘width’ and ‘area’ are used to store user input
and calculate the area of the rectangle.
A bit of history
The Bourne Shell (sh) was originally developed by Stephen Bourne while working at
Bell Labs.
Released in 1979 in the Version 7 Unix release distributed to colleges and
universities.
The Bourne Again Shell (bash) was written as a free and open source replacement
for the Bourne Shell.
Given the open nature of Bash, over time it has been adopted as the default shell on
most Linux systems.
First look at the command line
Now that we have covered some basics, let’s open a terminal window and see how
it looks!
At first, we entered the command ls which stands for list. By default this command
will print the content of the current directory.
Secondly, we have added an argument to ls by typing a space and -l. This argument
is changing the output format of ls and stands for “long listing format”.
Next, we have added another argument -h which stands for “human”, this argument
instructs the ls command to print file size in a human readable format.
Later on, we have combined two arguments, -l and -h in -lh which gives us the same
result and we have given a file name to “ls”. The result shows us only the file passed
as the last argument.
As a final example, we have replaced the short argument -h with its equivalent long
argument form --human-readable. As you can see, the command’s output didn’t
change.
Notes
There are a few important things to keep in mind when using a Linux shell:
It is case sensitive
In a Linux shell, commands, files and directory names are case sensitive meaning
that typing pwd will print the current working directory and typing PWD will return
an error similar to -bash: PWD: command not found
The / (forward-slash) is a special character used as directory separator
The Linux CLI is full of special characters, and we will go into more detail about this
topic. For the moment, just keep this in mind.
File extensions don’t matter
If you come from a windows background, a file with .exe extension means it is an
executable file. In Linux CLI, the file kind is determined automatically. (By reading
the file header).
Nearly every Linux command supports --help argument
During your journey with the CLI, you will often wonder “what argument do I need
to do X?” The answer is just a --help away.
The script will run with our specified arguments and use positional parameters to
generate an output. If you followed the step correctly, you should see the following
screen.
Reading Arguments
Our output shows the correct output by substituting the reserved variables with the
appropriate argument when we called it.
The process was run under the process ID 14974 and quit with the exit code 0.
What is Redirection?
Redirection is a feature in Linux such that when executing a command, you can
change the standard input/output devices. The basic workflow of any Linux
command is that it takes an input and give an output.
Redirection can be defined as changing the way from where commands read input
to where commands sends output. You can redirect input and output of a
command.
For redirection, meta characters are used. Redirection can be into a file (shell meta
characters are angle brackets '<', '>') or a program ( shell meta characters
are pipesymbol '|').
o standard input (stdin) '0<' or '<' : The stdin stream is numbered as stdin (0).
The bash shell takes input from stdin. By default, keyboard is used as input.
o standard output (stdout) '1>' or '>' : The stdout stream is numbered as
stdout (1). The bash shell sends output to stdout. Output goes to display.
o standard error (stderr) '2>' : The stderr stream is numbered as stderr (2). The
bash shell sends error message to stderr. Error message goes to display.
Output Redirection
The ‘>‘ symbol is used for output (STDOUT) redirection.
Example:ls -al > listings
Here the output of command ls -al is re-directed to file “listings” instead of your
screen.
Note: Use the correct file name while redirecting command output to a file. If there
is an existing file with the same name, the redirected command will delete the
contents of that file and then it may be overwritten.”
If you do not want a file to be overwritten but want to add more content to an
existing file, then you should use ‘>>‘ operator.
You can redirect standard output, to not just files, but also devices!
$ cat music.mp3 > /dev/audio
The cat command reads the file music.mp3 and sends the output to /dev/audio
which is the audio device. If the sound configurations in your PC are correct, this
command will play the file music.mp3
Input redirection
The ‘<‘ symbol is used for input(STDIN) redirection
Example: The mail program in Linux can help you send emails from the Terminal.
You can type the contents of the email using the standard device keyboard. But if
you want to attach a File to email you can use the input re-direction operator in the
following format.
Mail -s "Subject" to-address < Filename
This would attach the file with the email, and it would be sent to the recipient.
The above examples were simple. Let’s look at some advance re-direction
techniques which make use of File Descriptors.
Error Redirection: Error redirection is transferring the errors generated by some
false commands to a file rather than STDOUT.
Whenever a program is executed at the terminal, 3 files are generated: standard
input(0), standard output(1), standard error(2). These files are always created
whenever a program is run. By default, an error stream is displayed on the screen.
Examples:
1. In the below-mentioned example, the file descriptor used above is 2(STDERR).
Using “2>” re-directs the error output to a file named “error.txt” and nothing is
displayed on STDOUT.
$ somerandomcommand 2>error.txt
2. Here, 2>&1 means that STDERR redirects to the target of STDOUT. More
formally, the error message generated by “2” gets merged with the current output
“1“.
$ ls GEEK GFG > error.txt 2>&1
In the above example, the directory GEEK is not present. The error output is merged
with the standard output which in turn is being re-directed to “error.txt“.
Commands:
: ls, cat, find, cut, paste, grep, more, less, head, tail, date, who, whoami
(Both whoami and logname show the name of the current user) ,
w( the w command shows where users are logged in from and what they are
currently doing.),
How To Run a Process in Background in Linux?
Running processes in the background is a common requirement in Linux systems.
Running a process in the background allows you to continue using the terminal or
execute other commands while the process runs independently. This can be
particularly useful for long-running tasks or when you want to execute multiple
commands simultaneously. In this article, we will explore different methods on how
to run a process in background in Linux and understand how to manage them
effectively.
What is a Background Processes
Before we dive into the various methods, let's first understand what a background
process is. In Linux, a background process refers to a process that runs
independently of the terminal. When you execute a command, it typically runs in
the foreground, meaning it occupies the terminal until it completes. On the other
hand, running a process in the background allows you to execute other commands
while the process continues to run silently. In this article, we will explore the ins and
outs of how to run a process in background in Linux, equipping you with the
knowledge to manage background processes and enhance your overall Linux
experience efficiently.
How to Use the bg Command in Linux
One way to run a process in the background is by using the bg command.
The bg command is built-in to most Linux distributions and allows you to send a
running process to the background. Let's dive into the details of how to run a
process in background in Linux using the bg command and explore the steps
involved:
1. Start a process in the foreground by executing a command. For example, let's
say we want to compress a large file using the gzip command:
gzip largefile.txt
2. While the process is running, press Ctrl+Z to pause the process and bring it to
the background.
3. Use the bg command to resume the process in the background:
bg
The process will now continue running in the background, and you will see its job ID
displayed on the terminal. You can execute other commands while it progresses
silently. However, keep in mind that the process may still produce output, which can
appear on the terminal.
In the Linux operating system, jobs refer to processes that are running in the
background or foreground. Job control refers to the ability to manipulate these
processes, including suspending, resuming, and terminating them. This can be useful
for managing multiple tasks or for debugging problems with a process.
Understanding Processes and Jobs in Linux
In Linux, every program that is running is considered a process. A process can be a
standalone program or a part of a larger program.
Each process is assigned a unique identifier called a process ID (PID). The PID can be
used to refer to the process and perform actions on it, such as suspending or
terminating it.
A job is a process that is either running in the foreground or the background. The
foreground is the active window in the terminal, and the background is any process
that is running but not actively being used in the terminal.
By default, when you run a command in the terminal, it runs in the foreground. You
can tell that a process is running in the foreground because it displays output and
you cannot enter any more commands until it finishes.
To run a process in the background, you can use the & symbol at the end of the
command.
Example
$ sleep 30 &
[1] 12345
In this example, the sleep command causes the process to sleep for 30 seconds. The
& symbol causes the process to run in the background, and the output [1]
12345 indicates that it is job number 1 with a PID of 12345.
It hangup detected on
controlling terminals or
SIGHUP 1
death of controlling
process.
It interrupts from
SIGINT 2
keyboard.