Unit-I: Linux Programming B.Tech Iv Year Ii Sem (Kr21)
Unit-I: Linux Programming B.Tech Iv Year Ii Sem (Kr21)
UNIT-I
Introduction to Linux:
Linux is a Unix-like computer operating system assembled under the model of free
and open source software development and distribution. The defining component
of Linux is the Linux kernel, an operating system kernel first released 5 October
1991 by Linus Torvalds.
Linux was originally developed as a free operating system for Intel x86-based
personal computers. It has since been ported to more computer hardware platforms
than any other operating system. It is a leading operating system on servers and
other big iron systems such as mainframe computers and supercomputers more
than 90% of today's 500 fastest supercomputers run some variant of Linux,
including the 10 fastest. Linux also runs on embedded systems (devices where the
operating system is typically built into the firmware and highly tailored to the
system) such as mobile phones, tablet computers, network routers, televisions and
video game consoles; the Android system in wide use on mobile devices is built
on the Linux kernel.
A distribution oriented toward desktop use will typically include the X Window
System and an accompanying desktop environment such as GNOME or KDE
Plasma. Some such distributions may include a less resource intensive desktop
such as LXDE or Xfce for use on older or less powerful computers. A distribution
intended to run as a server may omit all graphical environments from the standard
install and instead include other software such as the Apache HTTP Server and an
SSH server such as OpenSSH. Because Linux is freely redistributable, anyone may
create a distribution for any intended use. Applications commonly
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
used with desktop Linux systems include the Mozilla Firefox web browser, the LibreOffice
office application suite, and the GIMP image editor
Basic Features:
Following are some of the important features of Linux Operating System.
Portable - Portability means software’s can works on different types of hardware’s in
same way. Linux kernel and application programs support their installation on any kind
of hardware platform.
Open Source - Linux source code is freely available and it is community-based
development project. Multiple Teams works in collaboration to enhance the capability of
Linux operating system and it is continuously evolving.
Multi-User - Linux is a multiuser system means multiple users can access system
resources like memory/ ram/ application programs at same time.
Multiprogramming - Linux is a multiprogramming system means multiple applications
can run at same time.
Hierarchical File System - Linux provides a standard file structure in which system
files/ user files are arranged.
Shell - Linux provides a special interpreter program which can be used to execute
commands of the operating system. It can be used to do various types of operations, call
application programs etc.
Security - Linux provides user security using authentication features like password
protection/ controlled access to specific files/ encryption of data.
Linux Advantages:
1.Low cost: You don’t need to spend time and money to obtain licenses since Linux and much
of its software come with the GNU General Public License. You can start to work immediately
without worrying that your software may stop working anytime because the free trial version
expires. Additionally, there are large repositories from which you can freely download high
quality software for almost any task you can think of.
2.Stability: Linux doesn’t need to be rebooted periodically to maintain performance levels.
It doesn’t freeze up or slow down over time due to memory leaks and such. Continuous up-
times of hundreds of days (up to a year or more) are not uncommon.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
core functionalities are the same; most software runs on most distributions.
8.Fast and easy installation: Most Linux distributions come with user-friendly installation
and setup programs. Popular Linux distributions come with tools that make installation of
additional software very user friendly as well.
9. Full use of hard disk: Linux continues work well even when the hard disk is almost full.
10. Multi-tasking: Linux is designed to do many things at the same time; e.g., a large printing
job in the background won’t slow down your other work.
11. Security: Linux is one of the most secure operating systems. “Walls” and flexible file access
permission systems prevent access by unwanted visitors or viruses. Linux users have to option
to select and safely download software, free of charge, from online repositories containing
thousands of high quality packages. No purchase transactions requiring credit card numbers or
other sensitive personal information are necessary.
12. Open Source: If you develop software that requires knowledge or modification of the
operating system code, LINUX’s source code is at your fingertips. Most Linux applications
are Open Source as well.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
by various vendors.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Usage Linux can be installed on a wide The UNIX operating system is used
variety of computer hardware, in internet servers, workstations &
ranging from mobile phones, PCs. Backbone of the majority of
tablet computers and video game finance infrastructure and many
consoles, to mainframes and 24x365 high availability solutions.
supercomputers.
File system Ext2, Ext3, Ext4, Jfs, ReiserFS, jfs, gpfs, hfs, hfs+, ufs, xfs, zfs format
support Xfs, Btrfs, FAT, FAT32, NTFS
Text mode BASH (Bourne Again SHell) is Originally the Bourne Shell. Now
interface the Linux default shell. It can it's compatible with many others
support multiple command including BASH, Korn & C.
interpreters.
Price Free but support is available for Some free for development use
a price. (Solaris) but support is available for
a price.
Security Linux has had about 60-100 A rough estimate of UNIX viruses is
viruses listed till date. None of between 85 -120 viruses reported till
them actively spreads date.
nowadays.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
10.5)/x86(10.4)/x64(10.5-10.8)
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
3.Debian Linux
4.Suse Enterprise Linux
5.Ubuntu Linux
Common things between Linux & UNIX
Both share many common applications such as: 1.GUI, file, and windows managers (KDE,
Gnome) 2.Shells (ksh, csh, bash)
3. Various office applications such as OpenOffice.org
4. Development tools (perl, php, python, GNU c/c++ compilers)
5. Posix interface
Layered Architecture:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
1. / – Root
Every single file and directory starts from the root directory.
Only root user has write privilege under this directory.
Please note that /root is root user’s home directory, which is not same as /.
2. /bin – User Binaries
Contains binary executables.
Common linux commands you need to use in single-user modes are located under this
directory.
Commands used by all the users of the system are located here.
For example: ps, ls, ping, grep, cp
3. /sbin – System Binaries
Just like /bin, /sbin also contains binary executables.
But, the linux commands located under this directory are used typically by system
aministrator, for system maintenance purpose.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
/usr/sbin contains binary files for system administrators. If you can’t find a system
binary under /sbin, look under /usr/sbin. For example: atd, cron, sshd, useradd, userdel
/usr/lib contains libraries for /usr/bin and /usr/sbin
/usr/local contains users programs that you install from source. For example, when you
install apache from source, it goes under /usr/local/apache2
10. /home – Home Directories
Home directories for all users to store their personal files.
For example: /home/john, /home/nikita
11. /boot – Boot Loader Files
Contains boot loader related files.
Kernel initrd, vmlinux, grub files are located under /boot
For example: initrd.img-2.6.32-24-generic, vmlinuz-2.6.32-24-generic
12. /lib – System Libraries
Contains library files that supports the binaries located under /bin and /sbin
Library filenames are either ld* or lib*.so.*
For example: ld-2.11.1.so, libncurses.so.5.7
13. /opt – Optional add-on Applications
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Linux Utilities:
cat linux command concatenates files and print it on the standard output.
SYNTAX:
The Syntax is
cat [OPTIONS] [FILE]...
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
Non-printing characters (with the exception of tabs, new-lines and form-feeds)
-v are printed visibly.
Example:
To Create a new file: cat >
file1.txt
This command creates a new file file1.txt. After typing into the file press control+d
(^d) simultaneously to end the file.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
To display a
file:cfile1.txt
The above cat command will concatenate the two files (file1.txt and file2.txt) and it will
display the output in the screen. Sometimes the output may not fit the monitor screen. In
such situation you can print those files in a nlew file or display the file using less command.
cat file1.txt file2.txt | less
rm COMMAND:
rm linux command is used to remove/delete the file from the directory.
SYNTAX:
The Syntax is
rm [options..] [file | directory]
OPTIONS:
EXAMPLE:
1. To Remove / Delete a file:
rm file1.txt
Here rm command will remove/delete the file file1.txt.
2. To delete a directory tree:
rm -ir tmp
This rm command recursively removes the contents of all subdirectories of the tmp
directory, prompting you regarding the removal of each file, and then removes the
tmp directory itself.
3. To remove more files at once
rm file1.txt file2.txt
rm command removes file1.txt and file2.txt files at the same time.
cd COMMAND:
cd command is used to change the directory.
SYNTAX:
The Syntax is cd [directory | ~ | ./ | ../ | - ]
OPTIONS:
-L Use the physical directory structure.
-P Forces symbolic links.
EXAMPLE:
1. cd linux-command
This command will take you to the sub-directory(linux-command) from its parent directory.
2. cd ..
This will change to the parent-directory from the current working directory/sub-directory.
3. cd ~
This command will move to the user's home directory which is "/home/username".
cp COMMAND:
cp command copy files from one location to another. If the destination is an existing file, then
the file is overwritten; if the destination is an existing directory, the file is copied into the directory
(the directory is not overwritten).
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
SYNTAX:
The Syntax is
cp [OPTIONS]... SOURCE DEST
cp [OPTIONS]... SOURCE... DIRECTORY
cp [OPTIONS]... --target-directory=DIRECTORY SOURCE...
OPTIONS:
-a same as -dpR.
--backup[=CONTROL] make a backup of each existing destination file
-b like --backup but does not accept an argument.
if an existing destination file cannot be opened, remove it and try
-f
again.
-p same as --preserve=mode,ownership,timestamps.
preserve the specified attributes
-
(default: mode,ownership,timestamps) and security
preserve[=ATTR_LIST]
contexts, if possible
additional attributes: links, all.
--no-
don't preserve the specified attribute.
preserve=ATTR_LIST
--parents append source path to DIRECTORY.
EXAMPLE:
Copy two
files: cp
file1
file2
The above cp command copies the content of file1.php to file2.php.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
ls COMMAND:
ls command lists the files and directories under current working directory.
SYNTAX:
The
Syntax is
ls [OPTIONS]... [FILE]
OPTIONS:
Lists all the files, directories and their mode, Number of links, owner of the
-l
file, file size, Modified date and time and filename.
-t Lists in order of last modification time.
-a Lists all entries including hidden files.
-d Lists directory files instead of contents.
-p Puts slash at the end of each directories.
-u List in order of last access time.
-i Display inode information.
-ltr List files order by date.
- List files order by file size.
lSr
EXAMPLE:
Display root directory contents: ls
/ lists the contents of root
directory.
1. Display hidden files anddirectories:
ls -a
lists all entries including hidden files and directories.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
7373073 book.gif
7373074 clock.gif
7373082 globe.gif
7373078 pencil.gif
7373080 child.gif
7373081 email.gif
7373076 indigo.gif
The above command displays filename with inode value.
ln COMMAND:
ln command is used to create link to a file (or) directory. It helps to provide soft link for
desired files. Inode will be different for source and destination.
SYNTAX:
The
Syntax
is
ln [options] existing file(or directory)name new file(or directory)name
OPTIONS:
Link files without questioning the user, even if the mode of target forbids
-f
writing. This is the default if the standard input is not a terminal.
-n Does not overwrite existing files.
-s Used to create soft links.
EXAMPLE:
1. ln -s file1.txt file2.txt
Creates a symbolic link to 'file1.txt' with the name of 'file2.txt'. Here inode for 'file1.txt'
and 'file2.txt' will be different.
2. ln -s nimi nimi1
Creates a symbolic link to 'nimi' with the name of 'nimi1'.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
chown COMMAND:
chown command is used to change the owner / user of the file or directory. This is an admin
command, root user only can change the owner of a file or directory.
SYNTAX:
The Syntax is
chown [options] newowner filename/directoryname
OPTIONS:
Change the permission on files that are in the subdirectories of the directory
-R
that you are currently in.
-c Change the permission for each file.
Prevents chown from displaying error messages when it is unable to change
-f
the ownership of a file.
EXAMPLE:
The owner of the 'test' directory is root, With -R option the files and subdirectories
user also gets changed.
Here change the owner for the specific 'calc.txt' file only.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Chmod Command:
chmod command allows you to alter / Change access rights to files and directories.
User
Group
Others
Permission 000
SYNTAX:
The Syntax is
chmod [options] [MODE] FileName
File Permission
# File Permission
0 none
1 execute only
2 write only
3 write and execute
4 read only
5 read and execute
6 read and write
7 set all permissions
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
OPTIONS:
-c Displays names of only those files whose permissions are being changed
-f Suppress most error messages
mkdir COMMAND:
mkdir command is used to create one or more directories.
SYNTAX:
The Syntax is
mkdir [options] directories
OPTIONS:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
EXAMPLE:
1. Create directory:
mkdir test
The above command is used to create the directory 'test'.
2. Create directory and set permissions:
mkdir -m 666 test
The above command is used to create the directory 'test' and set the read and write permission.
rmdir COMMAND:
rmdir command is used to delete/remove a directory and its subdirectories.
SYNTAX:
The Syntax is
rmdir [options..] Directory
OPTIONS:
Allow users to remove the directory dirname and its parent directories which
-p
become empty.
EXAMPLE:
1. To delete/remove a directory
rmdir tmp
rmdir command will remove/delete the directory tmp if the directory is empty.
This command recursively removes the contents of all subdirectories of the tmp directory,
prompting you regarding the removal of each file, and then removes the tmp directory
itself.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
mv COMMAND:
mv command which is short for move. It is used to move/rename file from one directory to
another. mv command is different from cp command as it completely removes the file from the
source and moves to the directory specified, where cp command just copies the content from one
file to another.
SYNTAX:
The Syntax is
mv [-f] [-i] oldname newname
OPTIONS:
EXAMPLE:
In the above line mv command moves all the files, directories and sub-directories from
hscripts folder/directory to tmp directory if the tmp directory already exists. If there is no
tmp directory it rename's the hscripts directory as tmp directory.
diff COMMAND:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
SYNTAX:
The Syntax is
diff [options..] from-file to-file
OPTIONS:
Use heuristics to speed handling of large files that have numerous scattered
-H
small changes.
EXAMPLE:
Lets create two files file1.txt and file2.txt and let it have the following data.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
HIOX TEST
HIOX TEST
hscripts.com
HSCRIPTS.com
with friend
with friend ship
ship hiox
india
< hscripts.com
---
> HSCRIPTS.com
4d3
< Hioxindia.com
Hioxindia.com <
The third line(with friend ship) in file2.txt has more blank spaces, but still the -b ignores
the blank space and does not show changes in the particular line, -y print out
the result side by side.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
This command will compare the files ignoring case(upper-case and lower-case) and
displays the following output.
HIOX TEST HIOX TEST
hscripts.com HSCRIPTS.com with
friend ship with friendship
chgrp COMMAND:
chgrp command is used to change the group of the file or directory. This is an admin command.
Root user only can change the group of the file or directory.
SYNTAX:
The Syntax is
chgrp [options] newgroup filename/directory name
OPTIONS:
Change the permission on files that are in the subdirectories of the directory
-R
that you are currently in.
-c Change the permission for each file.
-f Force. Do not report errors.
Hioxindia.com <
EXAMPLE:
chgrp hiox test.txt
The group of 'test.txt' file is root, Change to newgroup hiox.
1. chgrp -R hiox test
The group of 'test' directory is root. With -R, the files and its subdirectories also
changes to newgroup hiox.
2. chgrp -c hiox calc.txt
They above command is used to change the group for the specific file('calc.txt') only.
About wc
Short for word count, wc displays a count of lines, words, and characters in a file.
Syntax
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
-c Count bytes.
-m Count characters.
-C Same as -m.
-l Count lines.
Examples
13 = Words
57 =Characters
About split
Split a file into pieces.
Syntax
split [-linecount | -l linecount ] [ -a suffixlength ] [file [name] ] split -b n [k | m] [ -a suffixlength ] [ file [name]]
-a Use suffix length letters to form the suffix portion of the filenames of the split file.
suffixlen If -a is not specified, the default suffix length is 2. If the sum of the name operand
gth and the suffix length option-argument would create a filename exceeding
NAME_MAX bytes, an error will result; split will exit with a diagnostic message
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
File The path name of the ordinary file to be split. If no input file is given or file is -, the
standard input will be used.
name The prefix to be used for each of the files resulting from the split operation. If no name argument is
given, x will be used as the prefix of the output files. The combined length of the basename of prefix
and suffixlength cannot exceed
NAME_MAX bytes; see OPTIONS.
Examples
split -b 22 newfile.txt new - would split the file "newfile.txt" into three separate files called
newaa, newab and newac each file the size of 22.
split -l 300 file.txt new - would split the file "newfile.txt" into files beginning with the name
"new" each containing 300 lines of text each
About settime and touch
Change file access and modification time.
Syntax
touch [-a] [-c] [-m] [-r ref_file | -t time ] file settime [ -f ref_file ] file
-a Change the access time of file. Do not change the modification time unless -m is
also specified.
-c Do not create a specified file if it does not exist. Do not write any diagnostic
messages concerning this condition.
-m Change the modification time of file. Do not change the access time unless -a is
also specified.
-r ref_file Use the corresponding times of the file named by ref_file instead of the current
time.
Use suffixlength letters to form the suffix portion of the filenames of the split file.
suffixlen If -a is not specified, the default suffix length is 2. If the sum of the name operand
gth and the suffixlength option-argument would create a filename exceeding
NAME_MAX bytes, an error will result; split will exit with a diagnostic message
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
File The path name of the ordinary file to be split. If no input file is given or file is -, the
standard input will be used.
name
The prefix to be used for each of the files resulting from the split operation. If no
name argument is given, x will be used as the prefix of the output files. The
combined length of the base name of prefix and suffixlength cannot exceed
NAME_MAX bytes; see OPTIONS.
Examples
split -b 22 newfile.txt new - would split the file "newfile.txt" into three separate files called
newaa, newab and newac each file the size of 22.
split -l 300 file.txt new - would split the file "newfile.txt" into files beginning with the name
"new" each containing 300 lines of text each
About settime and touch
Change file access and modification time.
Syntax:
touch [-a] [-c] [-m] [-r ref_file | -t time ] file settime [ -f ref_file ] file
-a Change the access time of file. Do not change the modification time unless -m is
also specified.
-c Do not create a specified file if it does not exist. Do not write any diagnostic
messages concerning this condition.
-m Change the modification time of file. Do not change the access time unless -a is
also specified.
-r ref_file Use the corresponding times of the file named by ref_file instead of the current
time.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
-t time Use the specified time instead of the current time. time will be a decimal number
of the form:
[[CC]YY]MMDDhhmm [.SS]
-f ref_file Use the corresponding times of the file named by ref_file instead of the current time.
Examples
settime myfile.txt
touch newfile.txt
Creates a file known as "newfile.txt", if the file does not already exist. If the file already exists the
accessed
/ modification time is updated for the file newfile.txt
About comm
Select or reject lines common to two files.
Syntax
comm [-1] [-2] [-3 ] file1 file2
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Examples
PROCESS UTILITIES
ps Command:
ps command is used to report the process status. ps is the short name for Process Status.
SYNTAX:
The Syntax is ps
[options]
OPTIONS:
List information about all processes most frequently requested: all those
-a
except process group leaders and processes not associated with a terminal..
-A List information for all processes.
or e
-d List information about all processes except session leaders.
-e List information about every process now running.
-f Generates a full listing.
EXAMPLE:
1. ps
Output:
ID TTY TIME CMD
2540 pts/1 00:00:00 bash
2621 pts/1 00:00:00 ps
In the above example, typing ps alone would list the current running processes.
2. ps -f
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Output:
UID PID PPID C STIME TTY TIME CMD
nirmala 2540 2536 0 15:31 pts/1 00:00:00 bash
nirmala 2639 2540 0 15:51 pts/1 00:00:00
ps-f Displays full information about currently running
processes.
kill COMMAND:
kill command is used to kill the background process.
SYNTAX:
The Syntax is
kill [-s] [-l] %pid
OPTIONS:
Specify the signal to send. The signal may be given as a signal name or
-s
number.
Write all values of signal supported by the implementation, if no operand is
-l
given.
- Process id or job id.
pid
-9 Force to kill a process.
EXAMPLE:
About nice
Invokes a command with an altered scheduling priority.
Syntax
command The name of a command that is to be invoked. If command names any of the special
built-in utilities, the results are undefined.
Examples
nice +13 pico myfile.txt - runs the pico command on myfile.txt with an increment of +13.
About at
Schedules a command to be ran at a particular time, such as a print job late at night.
Syntax
atq lists the user's pending jobs, unless the user is the superuser; in that case, everybody's jobs
are listed. The format of the output lines (one for each job) is: Job number, date, hour, job
class.
at [-c | -k | -s] [-f filename] [-q queuename] [-m] -t time [date] [-l] [-r]
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
-t time Specifies at what time you want the command to be ran. Format hh:mm. am / pm
indication can also follow the time otherwise a 24-hour clock is used. A timezone
name of GMT, UCT or ZULU (case insensitive) can follow to specify that the time
is in Coordinated Universal Time. Other timezones can be specified using the TZ
environment variable. The below quick times can also be entered: midnight -
Indicates the time 12:00 am (00:00).
noon - Indicates the time 12:00 pm.
now - Indicates the current day and time. Invoking at - now will submit submit
an at-job for potentially immediate execution.
date Specifies the date you wish it to be ran on. Format month, date, year. The following
quick days can also be entered:
Examples:
at -m 01:35 < atjob = Run the commands listed in the 'atjob' file at 1:35AM, in addition all output
that is generated from job mail to the user running the task. When this command has been
successfully enter you should receive a prompt similar to the below example.
Commands will be executed using /bin/csh job 1072250520.a at Wed Dec 24
00:22:00 2003 at -l = This command will list each of the scheduled jobs as seen below.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
1072250520.a
Wed Dec 24 00:22:00 2003
at -r 1072250520.a = Deletes the job just created. or
atrm 23 = Deletes job 23.
If you wish to create a job that is repeated you could modify the file that executes the commands with
another command that recreates the job or better yet use the crontab command.
Note: Performing just the at command at the prompt will give you an error "Garbled Time",
this is a standard error message if no switch or time setting is given.
DISK UTILITIES
du (abbreviated from disk usage) is a standard Unix program used to estimate file space usage—
space used under a particular directory or files on a file system.
Du takes a single argument, specifying a path name for du to work; if it is not specified, the
current directory is used. The SUS mandates for du the following options:
-a, display an entry for each file (and not directory) contained in the current directory
-H, calculate disk usage for link references specified on the command line
-s, report only the sum of the usage in the current directory, not for each file
-x, only traverse files and directories on the device on which the pathname argument is specified.
the Unix and Unix-like operating systems may add extra options. For example, BSD and GNU du
specify a - h option, displaying disk usage in a format easier to read by the user, adding units with
the appropriate SI prefix’
$ du -sk *
152304 directoryOne
1856548 directoryTwo
Sum of directories in human-readable format (Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte):
$ du -sh *
149M directoryOne
1.8G directoryTwo
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
disk usage of all subdirectories and files including hidden files within the current directory
(sorted by filesize) :
disk usage of all subdirectories and files including hidden files within the current directory
(sorted by reverse filesize) :
$ du -d 1 -c -h
df command : Report file system disk space usage
Df command examples - to check free disk space
Type df -h or df -k to list free disk space:
$ df -h
OR
$ df –k
Output:
Filesystem Size Used Avail Use% Mounted on
/dev/sdb1 20G 9.2G 9.6G 49% /
varrun 393M 144k 393M 1% /var/run
varlock 393M 0 393M 0% /var/lock
procbususb 393M 123k 393M 1%
/proc/bus/usb udev 393M 123k
393M 1% /dev
devshm 393M 0 393M 0% /dev/shm
lrm 393M 35M 359M 9% /lib/modules/2.6.20-15-generic/volatile
/dev/sdb5 29G 5.4G 22G 20% /media/docs
/dev/sdb3 30G 5.9G 23G 21% /media/isomp3s
/dev/sda1 8.5G 4.3G 4.3G 51% /media/xp1
/dev/sda2 12G 6.5G 5.2G 56% /media/xp2
/dev/sdc1 40G 3.1G 35G 9% /media/backup
du command examples
du shows how much space one ore more files or directories is using.
$ du -sh 103M
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
-s option summarize the space a directory is using and -h option provides "Human-readable" output.
NETWORKING COMMANDS
These are most useful commands in my list while working on Linux server , this enables you
to quickly troubleshoot connection issues e.g. whether other system is connected or not ,
whether other host is responding or not and while working for FIX connectivity for
advanced trading system this tools saves quite a lot of time
This article is in continuation of my article How to work fast in Unix and Unix
Command tutorials and Examples for beginners.
let's see some example of various networking command in Unix and Linux. Some of them are
quite basic e.g. ping and telnet and some are more powerful e.g. nslookup and netstat. When you
used these commands in combination of find and grep you can get anything you are looking for
e.g. hostname, connection end points, connection status etc.
hostname
hostname with no options displays the machines host name
hostname –d displays the domain name the machine belongs to
hostname –f displays the fully qualified host and domain name
hostname –i displays the IP address for the current machine
ping
It sends packets of information to the user-defined source. If the packets are received,
the destination device sends packets back. Ping can be used for two purposes
1. To ensure that a network connection can be established.
2. Timing information as to the speed of the connection.
If you do ping www.yahoo.com it will display its IP address. Use ctrl+C to stop the test.
ifconfig
View network configuration, it displays the current network adapter configuration. It is handy to
determine if you are getting transmit (TX) or receive (RX) errors.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
netstat
Most useful and very versatile for finding connection to and from the host. You can find out
all the multicast groups (network) subscribed by this host by issuing "netstatg"netstat -nap |
grep port will display process id of application which is using that port netstat -a or netstat –
all will display all connections including TCP and UDP netstat --tcp or netstat –t will display
only TCP connection
etstat --udp or netstat –u will display only UDP connection netstat -g will display all multicast network subscribed
by this host. slookup
If you know the IP address it will display hostname. To find all the IP addresses for a given
domain name, the command nslookup is used. You must have a connection to the internet for
this utility to be useful.
E.g. nslookup blogger.com
You can also use nslookup to convert hostname to IP Address and from IP Address from hostname.
Traceroute
A handy utility to view the number of hops and response time to get to a remote system or
web site is traceroute. Again you need an internet connection to make use of this tool.
finger
View user information, displays a user’s login name, real name, terminal name and write status.
this is pretty old unix command and rarely used now days.
telnet
Connects destination host via telnet protocol, if telnet connection establish on any port means
connectivity between two hosts is working fine.
telnet hostname port will telnet hostname with the port specified. Normally it is used to see
whether host is alive and network connection is fine or not.
Linux is most powerful operating system which often needs to use commands to explore it
effectively.Some of the commands are restricted to normal user groups as they are powerful and
has more functionality involved in it.Here we summarized most interesting and useful networking
commands which every linux user are supposed to be familiar with it.
1. Arp manipulates the kernel’s ARP cache in various ways. The primary options are clearing an
address mapping entry and manually setting up one. For debugging purposes, the arp program
also allows a complete dump of the ARP cache.ARP displays the IP address assigned to particular
ETH card and mac address
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
[fasil@smashtech ]# arp
Address HWtype HWaddress Flags Mask Iface
59.36.13.1 ether C eth0
2. Ifconfig is used to configure the network interfaces. Normally we use this command tocheck
the IP address assigned to the system.It is used at boot time to set up interfaces as
necessary. After that, it is usually only needed when debugging or when system tuning is needed.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
5. Nslookup is a program to query Internet domain name servers. Nslookup has two modes:
interactive and non-interactive. Interactive mode allows the user to query name servers for
information about various hosts and domains or to print a list of hosts in a domain. Non-
interactive mode is used to print just the name and requested information for a host ordomain.
Non-authoritative
answer:
Name:google.com
Address:
209.85.171.100
Name:google.com
Address:
74.125.45.100
Name:google.com
Address:
74.125.67.100
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
6. dig (domain information groper) is a flexible tool for interrogating DNS name servers. It
performs DNS lookups and displays the answers that are returned from the name server(s) that
were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its
flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality
than dig.
;; QUESTION SECTION:
;google.com. IN A
;; ANSWER SECTION:
google.com. 122 IN A 74.125.45.100
google.com. 122 IN A 74.125.67.100
google.com. 122 IN A 209.85.171.100
;; AUTHORITY SECTION:
google.com. 326567 IN NS ns3.google.com.
google.com. 326567 IN NS ns4.google.com.
google.com. 326567 IN NS ns1.google.com.
google.com. 326567 IN NS ns2.google.com.
;; ADDITIONAL SECTION:
ns1.google.com. 152216 IN A 216.239.32.10
ns2.google.com. 152216 IN A 216.239.34.10
ns3.google.com. 152216 IN A 216.239.36.10
ns4.google.com. 152216 IN A 216.239.38.10
7. Route manipulates the IP routing tables. Its primary use is to set up static routes to specific
hosts or networks via an interface after it has been configured with the configure program.
When the add or del options are used, route modifies the routing tables. Without these options,
route displays the current contents of the routing tables.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
10.W-displays information about the users currently on the machine, and their processes. The
header shows, in this order, the current time, how long the system has been running, how many
users are currently logged on, and the system load averages for the past 1, 5, and 15 minutes.
[fasil@smashtechl ~] # w
FILTERS
more COMMAND:
more command is used to display text in the terminal screen. It allows only backward movement.
SYNTAX:
The Syntax is
more [options] filename
OPTIONS:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
EXAMPLE:
1. more -c index.php
Clears the screen before printing the file .
2. more -3 index.php
Prints first three lines of the given file. Press Enter to display the file line by line.
head COMMAND
head command is used to display the first ten lines of a file, and also specifies how many lines to display.
SYNTAX:
The Syntax is
head [options] filename
OPTIONS:
EXAMPLE:
1. head index.php
This command prints the first 10 lines of 'index.php'.
2. head -5 index.php
The head command displays the first 5 lines of 'index.php'.
3. head -c 5 index.php
The above command displays the first 5 characters of 'index.php'.
tail COMMAND:
tail command is used to display the last or bottom part of the file. By default it displays
last 10 lines of a file.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
SYNTAX:
The Syntax is tail [options] filename
OPTIONS:
-l To specify the units of lines.
-b To specify the units of blocks.
-n To specify how many lines you want to display.
The number option-argument must be a decimal integer whose sign affects the
-c
location in the file, measured in bytes.
number
The number option-argument must be a decimal integer whose sign affects the
n
number location in the file, measured in lines.
EXAMPLE:
tail index.php
It displays the last 10 lines of 'index.php'.
1. tail -2 index.php
It displays the last 2 lines of 'index.php'.
2. tail -n 5 index.php
It displays the last 5 lines of 'index.php'.
3. tail -c 5 index.php
It displays the last 5 characters of 'index.php'.
cut COMMAND:
cut command is used to cut out selected fields of each line of a file. The cut command uses
delimiters to determine where to split fields.
SYNTAX:
The Syntax is cut
[options]
OPTIONS:
EXAMPLE:
1. cut -c1-3 text.txt
Output:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
paste COMMAND:
paste command is used to paste the content from one file to another file. It is also used
to set column format for each line.
SYNTAX:
The Syntax is paste [options]
OPTIONS:
EXAMPLE:
1. paste test.txt>test1.txt
Paste the content from 'test.txt' file to 'test1.txt' file.
2. ls | paste - - - -
List all files and directories in four columns for each line.
sort COMMAND:
sort command is used to sort the lines in a text file.
SYNTAX:
The Syntax is
sort [options] filename
OPTIONS:
EXAMPLE:
1. sort test.txt
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
2. sort -r test.txt
Sorts the 'test.txt' file in reverse order and prints result in the screen.
About uniq Report or filter out repeated lines in a file.
Syntax
-c Precede each output line with a count of the number of times the line occurred in
the input.
-d Suppress the writing of lines that are not repeated in the input.
-s char Ignore the first chars characters when doing comparisons, where chars is a positive
decimal integer. If specified in conjunction with the -f option, the first chars
characters after the first fields fields will be ignored. If chars specifies more
characters than remain on an input line, a null string will be used for comparison.
input_file A path name of the input file. If input_file is not specified, or if the input_file is -
,the standard input will be used.
output_file
A path name of the output file. If output_file is not specified, the standard output
will be used. The results are unspecified if the file named by output_file is the file
named by input_file.
Examples
uniq myfile1.txt > myfile2.txt - Removes duplicate lines in the first file1.txt and outputs the
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
About tr
Translate characters.
Syntax
Examples
echo "12345678 9247" | tr 123456789 computerh - this example takes an echo response of
'12345678 9247' and pipes it through the tr replacing the appropriate numbers with the letters. In
this example it would return computer hope.
tr -cd '\11\12\40-\176' < myfile1 > myfile2 - this example would take the file myfile1 and strip
all non printable characters and take that results to myfile2.
Text processing utilities and Backup utilities: Text processing utilities:
echo $HOME
eg. wc file1.txt
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
wc L
file1.txt
[OPTION]... [FILE]...
eg. Sort
file1.txt sort r
file1.txt
General Commands:
date COMMAND:
date command prints the date and time.
SYNTAX:
The Syntax is
date [options] [+format] [date]
OPTIONS:
Slowly adjust the time by sss.fff seconds (fff represents fractions of a second).
-a
This adjustment can be positive or negative.Only system admin/ super user
can adjust the time.
- Sets the time and date to the value specfied in the date string. The date str may
date contain the month names, time zones, 'am', 'pm', etc.
-
-u Display (or set) the date in Greenwich Mean Time (GMT-universal time).
Format:
%a Abbreviated weekday(Tue).
% Full weekday(Tuesday).
A
%b Abbreviated month name(Jan).
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
%t Tab space.
who COMMAND:
who command can list the names of users currently logged in, their terminal, the time
they have been logged in, and the name of the host from which they have logged in.
SYNTAX:
The Syntax is
who [options] [file]
OPTIONS:
Print the username of the invoking user, The 'am' and 'i' must be space
am i
separated.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
EXAMPLE:
1. who –Uh
Output:
NAME LINE TIME IDLE PID COMMENT
hiox ttyp3 Jul 10 11:08 . 4578
This sample output was produced at 11 a.m. The "." indiacates activity within the last minute.
2. who am i
who am i command prints the user name.
echo COMMAND:
echo command prints the given input string to standard output.
SYNTAX:
The Syntax is
echo [options..] [string]
OPTIONS:
-n do not output the trailing newline
-e enable interpretation of the backslash-escaped characters listed below
-E disable interpretation of those sequences in STRINGs
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
EXAMPLE:
echo command
echo "hscripts Hiox India"
The above command will print as hscripts Hiox India
To use backspace:
echo -e "hscripts \bHiox \bIndia"
The above command will remove space and print as hscriptsHioxIndia
1. To use tab space in echo command
echo -e "hscripts\tHiox\tIndia"
The above command will print as hscripts Hiox India
passwd COMMAND:
passwd command is used to change your password.
SYNTAX:
The Syntax is passwd [options]
OPTIONS:
EXAMPLE:
1. passwd
Entering just passwd would allow you to change the password. After entering passwd
you will receive the following three prompts:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Current Password:
New Password:
Confirm New Password:
Each of these prompts must be entered correctly for the password to be successfully changed.
pwd COMMAND:
pwd - Print Working Directory. pwd command prints the full filename of the current working directory.
SYNTAX:
The Syntax is pwd [options]
OPTIONS:
EXAMPLE:
If you are working in home directory then, pwd command displays the current
working directory as /home.
cal COMMAND:
cal command is used to display the calendar.
SYNTAX:
The Syntax is
cal [options] [month] [year]
OPTIONS:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
EXAMPLE:
1. cal
Output:
September 2008
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
cal command displays the current month calendar.
2. cal -3 5 2008
Output:
April 2008 May 2008 June 2008
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 1 2 3 1 2 3 4 56 7
6 7 8 9 10 11 12 4 5 6 7 8 9 10 8 9 10 11 12 13
14
13 14 15 16 17 18 11 12 13 14 15 1615 16 17 18 19 20
19 17 21
20 21 22 23 24 25 18 19 20 21 22 2322 23 24 25 26 27
26 24 28
27 28 29 30 25 26 27 28 29 30 31 29 30
Here the cal command displays the calendar of April, May and June month of year 2008.
login Command
Syntax
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
-d device login accepts a device option, device. device is taken to be the path name of the
TTY port login is to operate on. The use of the device option can be expected to
improve login performance, since login will not need to call ttyname. The -d option
is available only to users whose UID and effective UID are root. Any
other attempt to use -d will cause login to quietly exit.
-h Used by in.telnetd to pass information about the remote host and terminal type.
hostname |
terminal
-r hostname Used by in. rlogin to pass information about the remote host.
Examples
uname command
-n Print the node name (the node name is the name by which the system is known to
a communications network).
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
-S
The node name may be changed by specifying a system name argument. The
Systemnam
system name argument is restricted to SYS_NMLN characters. SYS_NMLN is an
e
implementation specific value defined in <sys/utsname.h>.
Only the super- is allow this capability.
Examples
uname -arv
List the basic system information, OS release, and OS version as shown below.
SunOS hope 5.7 Generic_106541-08 sun4m sparc SUNW, SPARCstation-10
uname -p
SED
What is sed?
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Sed Operation:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
address determines which lines in the input file are to be processed by the command(s)
if no address is specified, then the command is applied to each input line
address types:
Single-Line address
Set-of-Lines address
Range address
Nested address
Single-Line Address
Examples:
show only line 3
sed -n -e '3 p' input-file
show only last line
sed -n -e '$ p' input-file
substitute “endif” with “fi” on line 10
sed -e '10 s/endif/fi/' input-file
Set-of-Lines Address
Examples:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Range Address
Defines a set of consecutive lines
Format:
start-addr,end-addr(inclusive)
Examples:
10,50 line-number,line-number
10,/R.E/line-number,/RegExp/
/R.E./,10/RegExp/,line-number
/R.E./,/R.E//RegExp/,/RegExp/
BEGIN
Line 4 of input
Line 5 of input
Nested Address
Nested address contained within another address
Example:
print blank lines between line 20 and 30
20,30{
/^$/ p
}
Address with !
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Line Number
line number command (=) writes the current line number before each matched/output line
Examples:
sed -e '/Two-thirds-time/=' tuition. data sed -e '/^[0-9][0-9]/=' inventory
modify commands
Insert Command: i
adds one or more lines directly to the output before the address:
inserted “text” never appears in sed’s pattern space
cannot be used with a range address; can only be used with the single-line andset-
of-lines address types
Syntax:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
[address] i\ text
Append Command: a
adds one or more lines directly to the output after the address:
Similar to the insert command (i), append cannot be used with a range address.
Appended “text” does not appear in sed’s pattern space.
Syntax:
[address] a\ text
Change Command: c
replaces an entire matched line with new text
accepts four address types:
Syntax:
[address1[,address2]] c\ text
Delete Command: d
commands following the delete command are ignored since the deleted text is no
Syntax:
[address1[,address 2]] d
Syntax:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
$ cat datafile
Patricia 4.0 .7 4 17
Hemenway
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Syntax: [addr1][,addr2]y/a/b/
Example:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
N (uppercase) Command
adds the next input line to the current contents of the pattern space
useful when applying patterns to two or more lines at the same time
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
prints the contents of the pattern space up to and including a new line character
any text following the first new line is notprinted
Hold Space
4 commands that can be used to move text back and forth between the pattern space and
the hold space:
h, H,g, G
File commands
allows to read and write from/to file while processing standard input
read: r command
write: w command
Read File command
Syntax: r filename
queue the contents of filename to be read and inserted into the output stream at
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
the end of the current cycle, or when the next input line is read
Syntax: [addr1][,addr2]b[label]
Branch label
mylabel
Same as:
% sed -n -e ‘1,50p’ datafile
% head -50 datafile
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
AWK
What is awk?
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Options:
-F to change input field separator
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Buffers
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
field buffer:
one for each fields in the current record.
names: $1, $2, …
record buffer :
$0 holds the entire record
filename
% cat
emps
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
% cat
emps
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
% cat em2
Tom Jones:4424:5/12/66:543354
Mary Adams:5346:11/4/63:28765
Sally Chang:1654:7/22/54:650000
Billy Black:1683:9/23/44:336500
awk Scripts
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Categories of Patterns
match
entire input record
o expression operators
arithmetic
relational
logical
% cat employees2
Tom Jones:4424:5/12/66:543354
Mary Adams:5346:11/4/63:28765
Sally Chang:1654:7/22/54:650000
Billy Black:1683:9/23/44:336500
% awk –F: '/00$/' employees2
Sally Chang:1654:7/22/54:650000
Billy Black:1683:9/23/44:336500
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
% cat
datafile
SO north NO
central CT
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
+ Add x+y
- Subtract x–y
* Multiply x*y
/ Divide x/y
% Modulus x%y
^ Exponential x^y
Example:
Relational Operators
== Equal to x == y
!= Not equal to x != y
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Logical Operators
Operator Meaning Example
|| Logical OR a || b
! NOT !a
Examples:
% awk '($2 > 5) && ($2 <= 15) {print $0}' file
Syntax:
pattern1 , pattern2 {action}
pattern can be any simple pattern
pattern1 turns action on
pattern2 turns action off
Range Pattern Example:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
AWK ACTIONS
awk expressions
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Examples:
Awk example:
File: grades
john 85 92 78 94 88
andrea 89 90 75 90 86
jasper 84 88 80 92 84
{ total = $2 + $3 + $4 + $5 + $6
avg = total / 5
Run as:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Output Statements:
print
print easy and simple output
printf
print formatted (similar to C printf)
sprint
format string (similar to C sprintf)
Function: print
john 85 92 78 94 88
andrea 89 90 75 90 86
john 85 92 78 94 88
andrea 89 90 75 90 86
john 85 92 78 94 88
andrea 89 90 75 90 86
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
> “file”
>> “file”
| “command”
will open file or command only once
subsequent redirections append to already open stream
print Example
% cat file
john 85
andrea 89
jasper 84
andrea 89
jasper 84
john 85
jasper 84
john 85
andrea 89
% date
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
% date |
Mo0nth: Nov
Year: 2008
Syntax:
%d %i decimal integer
%c single character
%s string of characters
%o octal number
%x hexadecimal number
Format specifier
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
examples
Format specifier
modifiers
%10s
%7d
%10.4f
%-20s
meaning:
width of field, field is printed right justified
precision: number of digits after decimal point
“-” will left justify sprintf: Formatting text
Syntax:
Example:
{
text = sprintf("1: %d – 2: %d", $1, $2) print text
}
AWK ARRAY
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Arrays in awk
Syntax:
arrayName[index] = value
Examples:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
divides string into pieces separated by fieldsep, and stores the pieces in array
if the fieldsep is omitted, the value of FS is used.
Example:
a[1] = "auto"
a[2] = "da"
a[3] = "fe"
input file:
output:
summary of category sales Illustration: process each input line.
.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
% cat sales.awk
{
deptSales[$2] += $3
}
END {
for (x in deptSales)
print x, deptSales[x]
}
% awk –f sales.awk sales
tolower(string)
toupper(string)
103:sway bar:49.99
101:propeller:104.99
104:fishing line:0.99
106:cup holder:2.49
107:cooler:14.89
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
112:boat cover:120.00
109:transom:199.00
110:pulley:9.88
105:mirror:4.99
108:wheel:49.99
111:lock:31.00
102:trailer hitch:97.95
Marine Parts R Us
Main catalog
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
======================================
BEGIN {
FS= ":"
print "======================================"
}
{
printf("%3d\t%-20s\t%6.2f\n", $1, $2, $3)
count++
}
END {
print "======================================"
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
APPLICATIONS
Conditional
if-else
Repetition
for
with counter
with array index
while
do-while
also: break, continue
if Statement
Syntax:
if (conditional expression)
statement-1
else
statement-2
Example:
if ( NR < 3 )
print $2
else
print $3
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
for Loop
Syntax:
Example:
total += $i
count++
}
Syntax:
Example:
for (x in deptSales)
print x, deptSales[x]
While Loop
Syntax:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Example:
i=1
print i, $i
i++
}
do
statement
while (condition)
Example:
i = 1
do {
print $0
i++
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
break
exits loop
continue
SHELL PROGRAMMING
The shell has similarities to the DOS command processor Command.com (actually Dos was
design as a poor copy of UNIX shell), it's actually much more powerful, really a programming
language in its own right.
A shell is always available on even the most basic UNIX installation. You have to go through the
shell to get other programs to run. You can write programs using the shell. You use the shell to
administrate your UNIX system. For example:
ls -al | more
is a short shell program to get a long listing of the present directory and route the output through
the more command.
What is a Shell?
A shell is a program that acts as the interface between you and the UNIX system, allowing
you to enter commands for the operating system to execute.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
The Bourne shell, or sh, was the default Unix shell of Unix Version 7. It was developed
by Stephen Bourne, of AT&T Bell Laboratories.
A Unix shell, also called "the command line", provides the traditional user interface for
the Unix operating system and for Unix-like systems. Users direct the operation of the
computer by entering command input as text for a shell to execute.
There are many different shells in use. They are
Bourne shell (sh)
C shell (csh)
Korn shell (ksh)
Bourne Again shell (bash)
When we issue a command the shell is the first agency to acquire the information. It
accepts and interprets user requests. The shell examines &rebuilds the commands
&leaves the execution work to kernel. The kernel handles the h/w on behalf of these
commands &all processes in the system.
The shell is generally sleeping. It wakes up when an input is keyed in at the prompt. This
input is actually input to the program that represents the shell.
Shell responsibilities
1. Program Execution
2. Variable and Filename Substitution
3. I/O Redirection
4. Pipeline Hookup
5. Environment Control
6. Interpreted Programming Language
1. Program Execution:
The shell is responsible for the execution of all programs that you request from your
terminal.
Each time you type in a line to the shell, the shell analyzes the line and the determines
what to do.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
The line that is typed to the shell is known more formally as the command line. The shell
scans this command line and determines the name of the program to be executed and what
arguments to pass to the program.
2. Variable and Filename Substitution:
Like any other programming language, the shell lets you assign values to variables.
Whenever you specify one of these variables on the command line, preceded by adollar
sign, the shell substitutes the value assigned to the variable at that point.
3. I/O Redirection:
It is the shell's responsibility to take care of input and output redirection on the command
line. It scans the command line for the occurrence of the special redirection characters <,
>, or >>.
4. Pipeline Hookup:
Just as the shell scans the command line looking for redirection characters, it also looks
for the pipe character |. For each such character that it finds, it connects the standard
output from the command preceding the | to the standard input of the one following the|.
It then initiates execution of both programs.
5. Environment Control:
The shell provides certain commands that let you customize your environment. Your
environment includes home directory, the characters that the shell displays to prompt you
to type in a command, and a list of the directories to be searched whenever you request
that a program be executed.
The shell has its own built-in programming language. This language is interpreted,
meaning that the shell analyzes each statement in the language one line at a time and then
executes it. This differs from programming languages such as C and FORTRAN, in which
the programming statements are typically compiled into a machine-executable form before
they are executed.
Programs developed in interpreted programming languages are typically easier to debug
and modify than compiled ones. However, they usually take much longer to execute the
their compiled equivalents.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Pipes connect processes together. The input and output of UNIX programs can be redirected.
Redirecting Output
The > operator is used to redirect output of a program. For example: ls -l >
lsoutput.txt
redirects the output of the list command from the screen to the file lsoutput.txt.
ps >> lsoutput.txt
Redirecting Input
Pipes
We can connect processes together using the pipe operator ( | ). For example, the following
program means run the ps program, sort its output, and save it in the file pssort.out
Here Documents
A here document is a special way of passing input to a command from a shell script. The
document starts and ends with the same leader after <<. For example:
#!/bin/sh
How It Works
You can type in a sequence of commands and allow the shell to execute them interactively,
or youu can sotre these commands in a file which you can invoke as a program.
Interactive Programs
A quick way of trying out small code fragments is to just type in the shell script on the command line.
Here is a shell program to compile only files that contain the string POSIX.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
To create a shell script first use a text editor to create a file containing the commands. For example, type the
following commands and save them as first.sh
The line
#!/bin/sh
is special and tells the system to use the /bin/sh program to execute this program.
The command
exit 0
Causes the script program to exit and return a value of 0, which means there were not errors.
There are two ways to execute the script. 1) invoke the shell with the name of the script file as a
parameter, thus:
/bin/sh first.sh
Or 2) change the mode of the script to executable and then after execute it by just
typing its name. chmod +x first.sh first.sh
Actually, you may need to type:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
./first.sh
to make the file execute unles the path variable has your directory in it.
Shell Syntax
The modern UNIX shell can be used to write quite large, structured programs.
Shell metacharacters
The shell consists of large no. of metacharacters. These characters plays vital role in Unix programming.
Types of metacharacters:
1.File substitution
2. I/O redirection
3. Process execution
4. Quoting metacharacters
5. Positional parameters
6. Special characters
7. Command substitution
Filename substitution
Shell Variables
Variables are generally created when you first use them. By default, all variables are considered and
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
U can define & use variables both in the command line and shell scripts. These variables
are called shell variables.
No type declaration is necessary before u can use a shell variable.
Variables provide the ability to store and manipulate the information with in the shell
program. The variables are completely under the control of user.
1.User-defined variables:
Generalized form:
variable=value.
Eg: $x=10
$echo $x
10
$unset x
All shell variables are initialized to null strings by default. To explicitly set null values
use
x= or x=‘’ or x=“”
Environment Variables
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
They are initialized when the shell script starts and normally
capitalized to distinguish them from user-defined variables in scripts
To display all variables in the local shell and their values, type the set command
The unset command removes the variable from the current shell and subshell
$# No . of parameters passed
read:
The read statement is a tool for taking input from the user i.e. making
scripts interactive. It is used with one or more variables. Input
supplied through the standard input is read into these variables.
$read name
name. printf:
Eg:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
o Every command returns a value after execution .This value is called the exit
status or return value of a command.
o This value is said to be true if the command executes successfully and false if it fails.
o There is special parameter used by the shell it is the $?. It stores the exit
status of a command.
exit:
o The exit statement is used to prematurely terminate a program. When this statement
is encountered in a script, execution is halted and control is returned to the calling
program- in most cases the shell.
o U don’t need to place exit at the end of every shell script because the shell
knows when script execution is complete.
set:
Set is used to produce the list of currently defined variables.
$set
It is a null command.
In some older shell scripts, colon was used at the start of a line to introduce a
comment, but modern scripts uses # now.
expr:
The expr command evaluates its arguments as an expression:
$ expr 8 + 6
$ x=`expr 12 / 4 `
$ echo $x
3
export:
There is a way to make the value of a variable known to a sub shell, and
that's by exporting it with the export command. The format of this
command is
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
export variables
where variables is the list of variable names that you want exported. For any sub shells
that get executed from that point on, the value of the exported variables will be passed
down to the sub shell.
eval:
eval scans the command line twice before executing it. General form for eval is eval
command-line
Eg:
$ cat last
${n}
If u supply more than nine arguments to a program, u cannot access the tenth and greater
arguments with $10, $11, and so on.
${n} must be used. So to directly access argument 10, you must write
${10}
Shift command:
The shift command allows u to effectively left shift your positional parameters. If u
execute the command
Shift
whatever was previously stored inside $2 will be assigned to $1, whatever was previously
stored in $3 will be assigned to $2, and so on. The old value of $1 will be irretrievably lost.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
It creates the variable salutation, displays its value, and some parameter variables.
When a shell starts, some variables are initialized from values in the environment.
Here is a sample of some of them.
Parameter Variables
If your script is invoked with parameters, some additional variables are created.
Quoting
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Normally, parameters are separated by white space, such as a space. Single quot marks can be
used to enclose values containing space(s). Type the following into a file called quot.sh
How It Works
The variable myvar is created and assigned the string Hi there. The content of the variable is
displyed using the echo $. Double quotes don't effect echoing the value. Single quotes and
backslash do.
Here is how to check for the existance of the file fred.c using the test and using the [] command.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
You can even place the then on the same line as the if, if youu add a semicolon before the word then.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Control Structures
if
The if statement is vary similar other programming languages except it ends with a fi.
if condition
then else fi
statements
elif
the elif is better known as "else if". It replaces the else part of an if statement with another if
statement. You can try it out by using the following script.
#!/bin/sh
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
exit 0
How It Works
The above does a second test on the variable timeofday if it isn't equal to yes.
which is illegal. This problem can be fixed by using double quotes around the variable name.
if [ "$timeofday" = "yes" ]
.
for
The for construct is used for looping through a range of values, which can be any set of strings.
The syntax is:
#!/bin/sh
bar
fud
0
43
How It Works
The above example creates the variable foo and assigns it a different value each time around the for loop.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
How It Works
Here is another script which uses the $(command) syntax to expand a list to chap3.txt,
chap4.txt, and chap5.txt and print the files.
#!/bin/sh
while
While loops will loop as long as some condition exist. OF course something in the body statements of
the loop should eventually change the condition and cause the loop to exit. Here is the while loop
syntax.
while condition do
statements
done
Here is a whil loop that loops 20 times. #!/bin/sh
foo=1
How It Works
The above script uses the [ ] command to test foo for <= the value 20. The line
foo=$(($fo0o+1))
increments the value of foo each time the loop executes..
until
The until statement loops until a condition becomes true! Its syntax is:
until condition do
statements
done
Here is a script using
until.
#!/bin/sh
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Sl0eep 60
done
echo -e \\a
echo "**** $1 has just loogged in ****" exit 0
case
The case statement allows the testing of a variable for more then one value. The case statement ends with
the word esac. Its syntax is:
case variable in
pattern [ | pattern] ...) statements;; pattern [ |
pattern] ...) statements;;
...
esac
Here is a sample script using a case statement:
#!/bin/sh
case "$timeofday" in
"yes") echo "Good Morning";; "no" ) echo
"Good Afternoon";; 0"y" ) echo "Good
Morning";; "n"
) echo "Good Afternoon";;
* ) echo "Soory, answer not recognized";;
esac exit 0
The value in the varaible timeofday is compared to various strings. When a match is made, the associated
echo command is executed.
Here is a case where multiple strings are tested at a time, to do the some action. case
"$timeofday" in
"yes" | "y" | "yes" | "YES" ) echo "good Morning";; "n"* |
"N"* ) <echo "Good Afternoon";;
* ) < echo "Sorry, answer not recognized";;
0esac
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
How It Works
The above has sever strings tested for each possible statement.
Here is a case statement that executes multiple statements for each case.
case "$timeofday" in
"yes" | "y" | "Yes" | "YES" ) echo "Good
Morning"
echo "Up bright and early this morning"
;;
esac
echo "Good Afternoon"
[nN]*) ;;
echo "Sorry, answer not recognized" echo "Please answer yes or noo"
When a match is found to the variable value of timeofday, all the statements up to the ;; are executed.
Arithmetic in shell
The $((...)) is a better alternative to the expr command, which allows simple arithmetic
commands to be processed.
x=$(($x+1))
Parameter Expansion
for i in 1 2
do
my_secret_process ${i}_tmp
done
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
How It Works
The try it out exercise uses parameter expansion to demonstrate how parameter expansion works.
read timeofday
else
fi
exit0
#!/bin/sh
timeofday
exit 1
fi exit 0
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Interrupt Processing-trap
The trap command is used for secifying the actions to take on receipt of signals. It syntax is:
Trap command signal Here are some of the signals.
How It Works
The try it out section has you type in a shell script to test the trap command. It creates a file and
keeps saying that it exists until you cause a control-C interrupt. It does it all again.
Functions
function_name ()
{
statements
}0
Here is a sample function and its
execution. #!/bin/sh
foo()
{ echo "Function foo is executing"
}
echo “script
starting “foo echo “script
ended”
exit 0
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
How It Works
When the above script runs, it defines the funcion foo, then script echos script starting, then
it runs the functions foo which echos Function foo is executing, then it echo script ended.
#!/bin/sh yes_or_no() {
echo "Parameters are $*"
while
true do
echo -n "Enter yes or no"
read x
0case "$x" in
y | yes ) return 0;; n
| no ) return 1;;
* )
echo "Answer yes or no"
esac
done
}
0exit 0
How It Works
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
Commands
You can execute normal command and built-in commands from a shell script. Built-in
commands are defined and only run inside of the script.
break
It is used to escape from an enclosing for, while or until loop before the controlling condition has been met.
The :Command
The colon command is a null command. It can be used for an alias for true..
Continue
The continue command makes the enclosing for, while, or until loop continue at the next iteration.
The Command
. shell_script
echo
The echo command simply outputs a string to the standard output device followed by a newline character.
Eval
exec
The exec command can replace the current shell with a different program. It can also modify the
current file descriptors.
exit n
The exit command causes the script to exit with exit code n. An exit code of 0 means success.
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
export
The export command makes the variable named as its parameter available in subshells.
expr
0x = `expr $x + 1`
Here are some of its expression evaluations
printf
The printf command is only available in more recent shells. It works similar to the echo
command. Its general form is:
Department of CSE
Linux Programming B.Tech IV Year II Sem (KR21)
return
The return command causes functions to return. It can have a value parameter which it returns.
set
The set command sets the parameter variables for the shell.
shift
The shift command moves all the parameters variables down by one, so $2 becomes $1, $3
becomes $2, and so on.
unset
Command Execution
The result of $(command) is simply the output string from the command, which is then available to the script.
Department of CSE
Linux Programming B.Tech IV Year II Sem
(KR21)
When an error occurs in a script, the shell prints out the line number with an error. You can use
the set command to set various shell option. Here are some of them.
Department of CSE
Linux Programming B.Tech IV Year II Sem
(KR21)
some_command
set +x # Disable debugging
echo "Script completed."
2. Use Echo Statements for Debugging
Insert echo statements to check variable values at different points:
bash
CopyEdit
echo "Value of VAR: $VAR"
3. Use trap for Error Handling
Capture signals and errors to execute custom debugging commands.
bash
CopyEdit
trap 'echo "Error at line $LINENO"; exit 1' ERR
4. Check for Syntax Errors
Use bash -n to check for syntax issues without executing the script.
bash
CopyEdit
bash -n script.sh
5. Use set -e to Exit on Errors
Stops the script if any command fails.
bash
CopyEdit
set -e
some_command # If this fails, the script stops here.
6. Debug Variable Expansion with declare -p
Print variable values and attributes:
bash
CopyEdit
declare -p VAR_NAME
Department of CSE
Linux Programming B.Tech IV Year II Sem
(KR21)
7. Use ps4 for Detailed Debugging
Customize debug output with PS4:
bash
CopyEdit
export PS4='+$BASH_SOURCE: $LINENO: '
set -x
8. Log Output for Later Analysis
Redirect output to a file for review:
bash
CopyEdit
bash -x script.sh > debug.log 2>&1
9. Use shellcheck for Static Analysis
Install and run shellcheck to detect potential issues.
bash
Copy Edit
shellcheck script.sh
10. Step Through with bash -v
Prints each line before execution:
bash
CopyEdit
bash -v script.sh.
Department of CSE