Linux Notes 1
Linux Notes 1
2. Creating Files
touch command can be used to create a new file. It will create and open a
new blank file if the file with a filename does not exist. And in case the file
already exists then the file will not be affected.
$touch filename
cat command can be used to display the contents of a file. This command
will display the contents of the ‘filename’ file. And if the output is very large
then we could use more or less to fit the output on the terminal screen
otherwise the content of the whole file is displayed at once.
$cat filename
4. Copying a File
cp command could be used to create the copy of a file. It will create the new
file in destination with the same name and content as that of the file
‘filename’.
$cp source/filename destination/
5. Moving a File
6. Renaming a File
7. Deleting a File
rm command could be used to delete a file. It will remove the filename file
from the directory.
$rm filename
A directory is a file the solo job of which is to store the file names and the related
information. All the files, whether ordinary, special, or directory, are contained in
directories.
Unix uses a hierarchical structure for organizing files and directories. This structure
is often referred to as a directory tree. The tree has a single root node, the slash
character (/), and all other directories are contained below it.
Home Directory
The directory in which you find yourself when you first login is called your home
directory.
You will be doing much of your work in your home directory and subdirectories that
you'll be creating to organize your files.
You can go in your home directory anytime using the following command −
$cd ~
$
Here ~ indicates the home directory. Suppose you have to go in any other user's
home directory, use the following command −
$cd ~username
$
To go in your last directory, you can use the following command −
$cd -
$
Creating Directories
We will now understand how to create directories. Directories are created by the
following command −
$mkdir dirname
Here, directory is the absolute or relative pathname of the directory you want to
create. For example, the command −
$mkdir mydir
$
Creates the directory mydir in the current directory. Here is another example −
$mkdir /tmp/test-dir
$
This command creates the directory test-dir in the /tmp directory.
The mkdir command produces no output if it successfully creates the requested
directory.
If you give more than one directory on the command line, mkdir creates each of the
directories. For example, −
$mkdir docs pub
$
Creates the directories docs and pub under the current directory.
Removing Directories
Directories can be deleted using the rmdir command as follows −
$rmdir dirname
$
Note − To remove a directory, make sure it is empty which means there should not
be any file or sub-directory inside this directory.
You can remove multiple directories at a time as follows −
$rmdir dirname1 dirname2 dirname3
$
The above command removes the directories dirname1, dirname2, and dirname3, if
they are empty. The rmdir command produces no output if it is successful.
Changing Directories
You can use the cd command to do more than just change to a home directory. You
can use it to change to any directory by specifying a valid absolute or relative path.
The syntax is as given below −
$cd dirname
$
Here, dirname is the name of the directory that you want to change to. For example,
the command −
$cd /usr/local/bin
$
Changes to the directory /usr/local/bin. From this directory, you can cd to the
directory /usr/home/amrood using the following relative path −
$cd ../../home/amrood
$
Renaming Directories
The mv (move) command can also be used to rename a directory. The syntax is as
follows −
$mv olddir newdir
$
You can rename a directory mydir to yourdir as follows −
$mv mydir yourdir
$
Read
Grants the capability to read, i.e., view the contents of the file.
Write
Grants the capability to modify, or remove the content of the file.
Execute
User with execute permissions can run a file as a program.
Write
Access means that the user can add or delete files from the directory.
Execute
Executing a directory doesn't really make sense, so think of this as a traverse
permission.
A user must have execute access to the bin directory in order to execute the ls or
the cd command.
Changing Permissions
To change the file or the directory permissions, you use the chmod (change mode)
command. There are two ways to use chmod — the symbolic mode and the absolute
mode.
Using chmod in Symbolic Mode
The easiest way for a beginner to modify file or directory permissions is to use the
symbolic mode. With symbolic permissions you can add, delete, or specify the
permission set you want by using the operators in the following table.
Sr.No. Chmod operator & Description
1
+
Adds the designated permission(s) to a file or directory.
2
-
Removes the designated permission(s) from a file or directory.
3
=
Sets the designated permission(s).
Here's an example using testfile. Running ls -1 on the testfile shows that the file's
permissions are as follows −
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on the testfile,
followed by ls –l, so you can see the permission changes −
$chmod o+wx testfile
$ls -l testfile
-rwxrwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod u-x testfile
$ls -l testfile
-rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod g = rx testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Here's how you can combine these commands on a single line −
$chmod o+wx,u-x,g = rx testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Here's an example using the testfile. Running ls -1 on the testfile shows that the file's
permissions are as follows −
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on the testfile,
followed by ls –l, so you can see the permission changes −
$ chmod 755 testfile
$ls -l testfile
-rwxr-xr-x 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 743 testfile
$ls -l testfile
-rwxr---wx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 043 testfile
$ls -l testfile
----r---wx 1 amrood users 1024 Nov 2 00:10 testfile
Changing Ownership
The chown command changes the ownership of a file. The basic syntax is as follows
−
$ chown user filelist
The value of the user can be either the name of a user on the system or the user id
(uid) of a user on the system.
The following example will help you understand the concept −
$ chown amrood testfile
$
Changes the owner of the given file to the user amrood.
NOTE − The super user, root, has the unrestricted capability to change the ownership
of any file but normal users can change the ownership of only those files that they
own.
Process States
The states that a Process enters in working from start till end are known as
Process states. These are listed below as:
Created-Process is newly created by system call, is not ready to
run
User running-Process is running in user mode which means it is a
user process.
Kernel Running-Indicates process is a kernel process running in
kernel mode.
Zombie- Process does not exist/ is terminated.
Preempted- When process runs from kernel to user mode, it is said
to be preempted.
Ready to run in memory- It indicated that process has reached a
state where it is ready to run in memory and is waiting for kernel to
schedule it.
Ready to run, swapped– Process is ready to run but no empty
main memory is present
Sleep, swapped- Process has been swapped to secondary storage
and is at a blocked state.
Asleep in memory- Process is in memory(not swapped to
secondary storage) but is in blocked state.
The numbers indicate the steps that are followed.
Process Transitions
Processes in Linux/Unix
A program/command when executed, a special instance is provided by the
system to the process. This instance consists of all the services/resources
that may be utilized by the process under execution.
Whenever a command is issued in Unix/Linux, it creates/starts a
new process. For example, pwd when issued which is used to list
the current directory location the user is in, a process starts.
Through a 5 digit ID number Unix/Linux keeps an account of the
processes, this number is call process ID or PID. Each process in
the system has a unique PID.
Used up pid’s can be used in again for a newer process since all
the possible combinations are used.
At any point of time, no two processes with the same pid exist in the
system because it is the pid that Unix uses to track each process.
Initializing a process
A process can be run in two ways:
Method 1: Foreground Process : Every process when started runs in
foreground by default, receives input from the keyboard, and sends output to
the screen. When issuing pwd command
$ ls pwd
Output:
$ /home/geeksforgeeks/root
When a command/process is running in the foreground and is taking a lot of
time, no other processes can be run or started because the prompt would not
be available until the program finishes processing and comes out.
$ kill 19
Terminated
If a process ignores a regular kill command, you can use kill -9 followed by
the process ID.
$ kill -9 19
Terminated
Other process commands:
bg: A job control command that resumes suspended jobs while keeping
them running in the background
Syntax:
bg [ job ]
For example:
bg %19
fg: It continues a stopped job by running it in the foreground.
Syntax:
fg [ %job_id ]
For example
fg 19
top: This command is used to show all the running processes within the
working environment of Linux.
Syntax:
top
nice: It starts a new process (job) and assigns it a priority (nice) value at the
same time.
Syntax:
nice [-nice value]
nice value ranges from -20 to 19, where -20 is of the highest priority.
renice : To change the priority of an already running process renice is used.
Syntax:
renice [-nice value] [process id]
df: It shows the amount of available disk space being used by file systems
Syntax:
df
Output:
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/loop0 18761008 15246876 2554440 86% /
none 4 0 4 0% /sys/fs/cgroup
udev 493812 4 493808 1% /dev
tmpfs 100672 1364 99308 2% /run
none 5120 0 5120 0% /run/lock
none 503352 1764 501588 1% /run/shm
none 102400 20 102380 1% /run/user
/dev/sda3 174766076 164417964 10348112 95% /host
free: It shows the total amount of free and used physical and swap memory
in the system, as well as the buffers used by the kernel
Syntax:
free
Output:
total used free shared buffers
cached
Mem: 1006708 935872 70836 0 148244
346656
-/+ buffers/cache: 440972 565736
Swap: 262140 130084 132056
Types of Processes
1. Parent and Child process : The 2nd and 3rd column of the ps –f
command shows process id and parent’s process id number. For
each user process, there’s a parent process in the system, with
most of the commands having shell as their parent.
2. Zombie and Orphan process : After completing its execution a
child process is terminated or killed and SIGCHLD updates the
parent process about the termination and thus can continue the
task assigned to it. But at times when the parent process is killed
before the termination of the child process, the child processes
become orphan processes, with the parent of all processes “init”
process, becomes their new pid.
A process which is killed but still shows its entry in the process
status or the process table is called a zombie process, they are
dead and are not used.
3. Daemon process : They are system-related background processes
that often run with the permissions of root and services requests
from other processes, they most of the time run in the background
and wait for processes it can work along with for ex print daemon.
When ps –ef is executed, the process with ? in the tty field are
daemon processes.
Linux signals
On Unix-like operating systems such
as Linux, signals are software interrupts. They provide a
way for the user (or a process) to directly communicate with
a process.
Description
Process signals were developed as part of UNIX in the 1970s. They
are used on all modern Unix-like operating systems,
including Linux, BSD, and macOS X.
Signals can be sent with the kill command, which is named for its
default signal (SIGKILL) that instructs the OS to forcefully
terminate a process before doing anything else.
Signals in Linux
Signal Number Description
SIGHUP 1 The HUP signal is sent to a process when its controlling POSIX
used.
a core dump.
privileged instruction.
SIGTRAP 5 Trace trap. The TRAP signal is sent to a process when a POSIX
SIGABRT, 6 Abort process. ABRT is usually sent by the process itself, 4.2 BSD
SIGBUS 7 The BUS signal is sent to a process when it causes 4.2 BSD
end.
SIGALRM 14 The ALRM signal notifies a process that the time interval POSIX
expired.
signal.
read from the tty while in the background. This signal can
to TTIN.
SIGURG 23 The URG signal is sent to a process when a socket has 4.2 BSD
SIGXCPU 24 The XCPU signal is sent to a process when it has used up 4.2 BSD
SIGVTALRM 26 Virtual alarm clock. May be sent by the alarm() system 4.2 BSD
SIGWINCH 28 Window change. The WINCH signal is sent to a process 4.3 BSD, Sun
SIGPWR, 30 Power failure. The PWR signal is sent to a process when System V
SIGE MT The EMT signal is sent to a process when an emulator trap occurs. Unused in Linux.
SIGINFO The INFO signal is sent to a process when a status request is received from the controlling terminal. Unused in L
SIGLOST The LOST signal is sent to a process when a file lock is lost. Unused in Linux.
SIGSYS The SYS signal is sent to a process when it passes a bad argument to a system call. Unused in Linux.
Real-time signals
Real-time signals are a set of signals with no predefined purpose,
for programmers to use as they want in their software. Two signal
names, SIGRTMIN and SIGRTMAX, define the minimum and
maximum signal numbers of the real-time signals. For example, the
programmer may use the signal number as SIGRTMIN+3 to refer
to the fourth real-time signal number.
kill 1234
kill -l
kill -9 -1
The special process ID -1 refers to all processes other than kill and
the system root process. This command attempts to kill (-9) every
possible process (-1) on the system. For more information, see the
documentation of kill, linked below.
Process creation
A new process is created because an existing process makes an exact copy of itself.
This child process has the same environment as its parent, only the process ID
number is different. This procedure is called forking.
After the forking process, the address space of the child process is overwritten with
the new process data. This is done through an exec call to the system.
The fork-and-exec mechanism thus switches an old command with a new, while the
environment in which the new program is executed remains the same, including
configuration of input and output devices, environment variables and priority. This
mechanism is used to create all UNIX processes, so it also applies to the Linux
operating system. Even the first process, init, with process ID 1, is forked during
the boot procedure in the so-called bootstrapping procedure.
This scheme illustrates the fork-and-exec mechanism. The process ID changes after
the fork procedure:
Every now and then things go wrong, even in good families. In an exceptional case,
a process might finish while the parent does not wait for the completion of this
process. Such an unburied process is called a zombie process.
In the Linux ecosystem, when we are running any application or any job. Every application or job will
run with a specific process ID or daemon or service. The process ID is nothing but a digit number.
Sometimes the job or any service may not run due to some issues like deadlock, process stuck, etc.
Due to which remaining jobs will impact coming from the same service. If such a condition may
happen, we need to kill or terminate the stuck job or process.
kill: We can use the “kill” keyword in the syntax or command to terminate the process. It will
accept the two arguments like OPTION and PROCESS ID. As per the provided input
arguments, the “kill” command will terminate the process.
OPTION: We can provide the different flags as options that are compatible with the “ps” and
“kill” command.
PROCESS ID: We need to provide the relevant process ID to terminate the process.
As we have discussed earlier, every job or application is running with a specific process ID. In the
background, we are able to get all the list of the running process in the Linux environment. Due to
some technical issues like deadlock, process or services stuck the job or application will not able to
run. Hence we need to terminate the stuck process. So the next upcoming jobs will be executed
perfectly fine.
In the Linux environment, if we need to kill the process. First, we need to identify the process and
get the relevant process id. There are different ways to get the process id from the Linux
environment like “ps” and “top”.
“ps” command.
ps -ax
“top” command.
To terminate the process, we need to use the below different killing signals in the kill command.
1. SIGHUP
2. SIGINT
3. SIGSTOP
To use SIGINT signal, we need to use the digit “17, 19, 23”
4. SIGTERM
5. SIGKILL
While terminating the Linux process, it is very important to identify the running process. There are
different ways to identify the running process.
Command:
ps -aux
Output:
Explanation: As per the above command, we are able to get all the running
process information on the Linux server. From the first “ps” command, we are the
entire list down all the process (refer to screenshot 1 (a)). But it is very difficult to
identify the specific process. To overcome this condition, we need to use the “pipe
(|)” functionality and grep the data from it (refer to screenshot 1 (b)).
command sends an exact signal to the process. In different ways, we can trigger the
Command:
kill -9 1941
Output:
Explanation: As discussed earlier, we are having different signals in the kill
command. As per the requirement, we can use those signals. In the above “kill”
command. We are using the kill signal i.e. “9”. The process id “1941” is running in
the environment. We are terminating the “1941” process with the help of kill signal
(9).
Command:
pkill httpd
Output:
Explanation: Sometimes we don’t have time to check all process ids and
terminate the process accordingly. Hence we need functionality to kill the process
via service, process or application name. To terminate the process, we can use the
process name with pkill command. As per the below screenshot, we have used the
“https” as the process name. It will terminate all the processes running with the
same name.
Command:
killall httpd
Output:
Explanation: If we need to terminate all the processes like a parent as well as
child process both then we need to use the “killall” command. As per the below
screenshot, we are using the “httpd” process name in the “killall” command. It will
terminate all the parent and child processes. Once, the “killall” command will
terminate the process. The status of the service or application is in a failed state.
One Time Task Scheduling using
at Command in Linux
While working with Linux systems we preferred crontab for scheduling jobs
generally. There are another utility at command is very useful for scheduling one time
tasks. It reads commands from standard input or script/file which can be executed later
once. But we can’t use at command for any recurring tasks. For recurring tasks use
Linux crontab.
At command can be useful for shutdown system at the specified time, Taking a one-
time backup, sending email as a reminder at the specified time etc. This article will
help you to understand the working of at command with useful examples.
at
03-23 09:00
at> ^d
1 2013-03-23 12:00 a ro
ot
Fields description:
First filed: job id
Second filed: Job execution date
third filed: Job execution time
Last field: User name, under which job is scheduled.
at -c 5
In the above example, 5 is the job id.
Examples of at Command:
at midnight
Here, the output will be by default stored in nohup.out. To redirect it, type:
$ nohup bash -c 'commands' > filename.txt
Example:
$ nohup bash -c 'cal && ls' > output.txt
Output:
Chapter 3
Linux Text Editors
Linux text editors can be used for editing text files, writing codes, updating user
instruction files, and more. A Linux system supports multiple text editors. There are
two types of text editors in Linux, which are given below:
A text editor plays an important role while coding. So, it is important to select the best
text editor. A text editor should not only be simple but also functional and should be
good to work with.
In this section, we are going to discuss the top 20 text editors for Linux
. Further, we will talk about the latest text editors and will compare them with the traditional text
editors such as Vi and nano. This will help you with selecting the editor of your choice.
1.Vi/VIM editor
Vim editor is one of the most used and powerful command-line based editor of the
Linux system. By default, it is supported by most Linux distros. It has enhanced
functionalities of the old Unix Vi editor
. It is a user-friendly editor and provides the same environment for all the Linux distros. It is also
termed as programmer's editor because most programmers prefer Vi editor.
Vi editor has some special features such as Vi modes and syntax highlighting that
makes it powerful than other text editors. Generally, it has two modes:
Insert Mode: The insert mode allows to insert text on files. To switch from command
mode to insert mode, press the Esc key to exit from active mode and 'i' key.
.
To invoke the vi editor, execute the vi command with the file name as follows:
1. vi <file name>
2. Nano editor
Nano is a straight forward editor. It is designed for both beginners and advanced users.
It has many customization features.
In the nano editor, the useful options are given at the bottom, use the CTRL+
option to perform an operation. For example, to exit from the editor, use CTRL
+X keys. To learn more about nano editor, Visit Linux Nano Editor
.
3. Gedit editor
Gedit editor is the default editor for the GNOME desktop environment. When we open
a file, it will open with the Gedit editor. It provides straightforward functionalities like
any basic text editor. It is a lightweight editor with a straight forward user interface. It
was publicly released in the year 2000 with a GNOME desktop environment. It is
developed using the C programming language
To invoke the gedit editor from the terminal, execute the below command:
It looks like:
Vi Editor with Commands
What is vi
The vi editor is elaborated as visual editor. It is installed in every Unix system. In other
words, it is available in all Linux distros. It is user-friendly and works same on different
distros and platforms. It is a very powerful application. An improved version of vi editor
is vim.
o Command Mode: In command mode, actions are taken on the file. The vi editor starts
in command mode. Here, the typed words will act as commands in vi editor. To pass a
command, you need to be in command mode.
o Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will
take you to the command mode from insert mode.
By default, the vi editor starts in command mode. To enter text, you have to be in insert
mode, just type 'i' and you'll be in insert mode. Although, after typing i nothing will
appear on the screen but you'll be in insert mode. Now you can type anything.
To exit from insert mode press Esc key, you'll be directed to command mode.
If you are not sure which mode you are in, press Esc key twice and you'll be in
command mode.
Using vi
The vi editor tool is an interactive tool as it displays changes made in the file on the
screen while you edit the file.
In vi editor you can insert, edit or remove a word as cursor moves throughout the file.
Commands are specified for each function like to delete it's x or dd.
The vi editor is case-sensitive. For example, p allows you to paste after the current line
while P allows you to paste before the current line.
vi syntax:
1. vi <fileName>
In the terminal when you'll type vi command with a file name, the terminal will get
clear and content of the file will be displayed. If there is no such file, then a new file
will be created and once completed file will be saved with the mentioned file name.
Linux vi example
To start vi open your terminal and type vi command followed by file name. If your file is in
some other directory, you can specify the file path. And if in case, your file doesn't exist, it will
create a new file with the specified name at the given location.
Example:
1. vi /home/sssit/Downloads/file.txt
Look at the above snapshot, we are creating a new file file.txt (as this file doesn't exist) and
have entered the full path for the directory Downloads.
Command mode
This is what you'll see when you'll press enter after the above command. If you'll start
typing, nothing will appear as you are in command mode. By default vi opens in
command mode.
Look at the above snapshot, it is blank as it is a new file. To start typing, you have to
move to the insert mode. At the end of the terminal window, directory name and file
name are displayed.
Insert mode
To move to the insert mode press i. Although, there are other commands also to move to
insert mode which we'll study in next page.
Look at the above snapshot, after pressing i we have entered into insert mode. Now we can
write anything. To move to the next line press enter.
Once you have done with your typing, press esc key to return to the command
mode.
To save and quit
You can save and quit vi editor from command mode. Before writing save or quit command
you have to press colon (:). Colon allows you to give instructions to vi.
exit vi table:
Commands Action
:w Save
:q Quit
To exit from vi, first ensure that you are in command mode. Now, type :wq and press enter. It
will save and quit vi.
If you want to quit without saving the file, use :q. This command will only work when you
have not made any changes in the file.
Look at the above snapshot, this file is modified and hence on typing :q it displays this
message at bottom left corner.
The above file can be saved with the command :!q. It discards the changes made in the file
and save it.
Look at the above snapshot, we have typed :!q, it will save our file by discarding the
changes made.
J To move down
K To move up
H To move left
L To move right
To jump lines:
Commands Action
To delete:
Commands Action
D Delete the current line from current character to the end of the line
dd Delete a line
Search a string:
Commands Action
/\<he\> Search for the word he (and not for there, here, etc.)
Replace all
Syntax:
1. :<startLine,endLine> s/<oldString>/<newString>/g
Example:
Commands Action
:1,$ s/readable/changed/ Replace forward with backward from first line to the last line
:3,6 s/letters/neww/g Replace forward with backward from third line to the ninth line
In above screenshot “ls” command with “-l” option is executed.It will list all the
files in current working directory in long listing format.
Working with command line shell is bit difficult for the beginners because it’s hard
to memorize so many commands. It is very powerful, it allows user to store
commands in a file and execute them together. This way any repetitive task can
be easily automated. These files are usually called batch files in Windows
and Shell Scripts in Linux/macOS systems.
Graphical Shells
Graphical shells provide means for manipulating programs based on graphical
user interface (GUI), by allowing for operations such as opening, closing, moving
and resizing windows, as well as switching focus between windows. Window OS
or Ubuntu OS can be considered as good example which provide GUI to user for
interacting with program. User do not need to type in command for every
actions.A typical GUI in Ubuntu system –
GUI shell
There are several shells are available for Linux systems like –
BASH (Bourne Again SHell) – It is most widely used shell in Linux systems.
It is used as default login shell in Linux systems and in macOS. It can also
be installed on Windows OS.
CSH (C SHell) – The C shell’s syntax and usage are very similar to the C
programming language.
KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell
standard specifications etc.
Each shell does the same job but understand different commands and
provide different built in functions.
Shell Scripting
Usually shells are interactive that mean, they accept command as input from
users and execute them. However some time we want to execute a bunch of
commands routinely, so we have type in all commands each time in terminal.
As shell can also take commands as input from file we can write these
commands in a file and can execute them in shell to avoid this repetitive
work. These files are called Shell Scripts or Shell Programs. Shell scripts
are similar to the batch file in MS-DOS. Each shell script is saved
with .sh file extension eg. myscript.sh
A shell script have syntax just like any other programming language. If you
have any prior experience with any programming language like Python,
C/C++ etc. it would be very easy to get started with it.
A shell script comprises following elements –
Shell Keywords – if, else, break etc.
Shell commands – cd, ls, echo, pwd, touch etc.
Functions
Control flow – if..then..else, case and shell loops etc.
Why do we need shell scripts
There are many reasons to write shell scripts –
To avoid repetitive work and automation
System admins use shell scripting for routine backups
System monitoring
Adding new functionality to the shell etc.
Advantages of shell scripts
The command and syntax are exactly the same as those directly entered in
command line, so programmer do not need to switch to entirely different
syntax
Writing shell scripts are much quicker
Quick start
Interactive debugging etc.
Disadvantages of shell scripts
Prone to costly errors, a single mistake can change the command which
might be harmful
Slow execution speed
Design flaws within the language syntax or implementation
Not well suited for large and complex task
Provide minimal data structure unlike other scripting languages. etc
Syntax:
1. echo $SHELL
Look at the above snapshot, with the help of above command we got the name of our
shell which is 'bash'.
The $ sign stands for a shell variable; echo will return the text whatever you typed in.
To run your script in a certain shell (shell should be supported by your system), start
your script with #! followed by the shell name.
Example:
1. #!/bin/bash
2. echo Hello World
3. #!/bin/ksh
4. echo Hello World
Look at the above snapshot, commented lines are not displayed in the output.
Shell Scripting Variables
Scripts can contain variables inside the script.
Look at the above snapshot, two variables are assigned to the script $var1 and $var2.
As scripts run in their own shell, hence variables do not survive the end of the script.
Look at the above snapshot, var1 and var2 do not run outside the script.
Note: In the last step you have to mention the path of the script if your script is in other
directory.
Look at the above snapshot, script echo Hello World is created with echo command
as hello_world. Now command chmod +x hello_world is passed to make it executable.
We have given the command ./hello_world to mention the hello_world path. And output is
displayed.
Syntax:
We have shown the example of voting. If user's age will be greater than 18 then he or she will
be eligible to vote, otherwise not.
1. if condition:
2. if [ "$age" -ge 18 ];
Look at the above snapshot, we have shown the script of file voter.
Look at the above snapshot, with age 17 it displays the message "you are younger !!" and
with age 30 it displays the message "you are eligible to vote".
Syntax:
Condition:
1. if [ $color == Red ]
2. elif [ $color == Blue ]
Condition:
1. if [ $color == Red ]
2. elif [ $color == Blue ]
Syntax:
Look at the above snapshot, you can write one pattern or more than one pattern
together according to the situation. Let's see an example to understand it more clearly.
Example:P
Look at the above snapshot, we have shown a script to show the capital of different
states. States Punjab and Haryana are written together as they share same capital.
Output:
Look at the above snapshot, user can enter a state name and script will display its
capital respectively.
Example for:
We have shown an example to count 2's table within for loop.
Look at the above snapshot, our varname is table, list is specified under curly braces. Within
the curly braces, first two will initialize the table from 2, 20 represents maximum value of
$table and last 2 shows the increment by value 2.
Look at the above snapshot, it displays the 2's table as the output.
2) Syntax:
Example for:
We have shown an example to count the number in reverse direction.
Look at the above snapshot, this is the loop script. $i will initialize with 10 and will go
till 1, decrementing with 1 value.
Look at the above snapshot, this is the output of the script.
Syntax:
Example:
We have shown the example of printing number in reverse order.
Syntax:
Syntax of until loop is shown in the snapshot below:
Example:
We have shown an example to display number from 5 to 15.
Look at the above snapshot, it displays the output until the condition is false.
Symbol Descriptions
Only lines that start with character are filtered. Lines which do not contain the
character ‘a’ at the start are ignored.
Expression Description
{n} Matches the preceding character appearing ‘n’ times exactly
{n,m} Matches the preceding character appearing ‘n’ times but not more than m
{n, } Matches the preceding character only when it appears ‘n’ times or more
Example:
We want to check that the character ‘p’ appears exactly 2 times in a string one
after the other. For this the syntax would be:
cat sample | grep -E p\{2}
Expression Description
Brace expansion
The syntax for brace expansion is either a sequence or a comma separated list
of items inside curly braces “{}”. The starting and ending items in a sequence
are separated by two periods “..”.
ome examples:
In the above examples, the echo command creates strings using the brace
expansion.