History, Linux Foundation, Linux Requirements, Linux Components
History, Linux Foundation, Linux Requirements, Linux Components
On
History, Linux Foundation, Linux
Requirements, Linux Components
Dated: 05-07-2021
Being open source does not just mean that you can see how the system works.
You can also experiment with changes and share them freely for others to use. The
open source model means that improvements are easier to make, enabling faster
innovation.
Linux provides easy access to a powerful and scriptable command-line interface
(CLI).
Linux was built around the basic design philosophy that users can perform all
administration tasks from the CLI. It enables easier automation, deployment, and
provisioning, and simplifies both local and remote system administration. Unlike
other operating systems, these capabilities have been built in from the beginning,
and the assumption has always been to enable these important capabilities.
Linux is a modular operating system that allows you to easily replace or remove
components.
Components of the system can be upgraded and updated as needed. A Linux
system can be a general-purpose development workstation or an extremely
stripped-down software appliance.
SUSE
The relationship between SUSE, SUSE Linux Enterprise Server
(SLES), and openSUSE is similar to the one described
between Fedora, Red Hat Enterprise Linux, and CentOS. In this
case, we decided to use openSUSE-Leap-42.2 as the reference
distribution for the SUSE family, as it is available to end users at no
cost. Because the two products are extremely similar, the material
that covers openSUSE can typically be applied to SLES with few
problems.
Jatin Arora Introduction to Linux G25
Some of the key facts about the SUSE family are listed below:
SUSE Linux Enterprise Server (SLES) is upstream
for openSUSE.
Kernel version 4.4 is used in openSUSE-Leap-42.2.
It uses the RPM-based zypper package manager (we cover
it in more detail later) to install, update, and remove
packages in the system.
It includes the YaST (Yet Another Setup Tool) application
for system administration purposes.
SLES is widely used in retail and other sectors.
Which of the following communication channels does the Linux community use to communicate?
1. cnn.com
2. IRC Channels
3. Mailing Lists
4. Community Events
What is a kernel?
1. The glue between hardware and applications.
2. A collection of software making up a Linux-based Operating System.
3. A program that runs as a background process.
4. A graphical subsystem on nearly all Linux systems.
ITL CS110 3
ITL CS110 4
BIOS - The First Step
Windows Linux
Man
Help
History
Who, Whoami
id
uname, uptime,
free, tty, cal,
date, hostname, reboot,
clear, bc.
su, sudo
Most input lines entered at the shell prompt have three basic elements:
• Command
• Options
• Arguments.
sudo ls –l /root
sudo cat /etc/passwd
ITL CS110 9
Mr. Jatin Arora - G25 Linux kernel API (internal kernel calls)14
Info
• Info documentation is comprehensive and hyperlinked. It is possible to
output info pages to multiple formats. By contrast, man pages are
optimized for printed output. Info nodes are read from the command
line, using the pinfo command.
• A typical man page has a small amount of content focusing on one
particular topic, command, tool, or file. The Info documentation is a
comprehensive document. Info provides the following improvements:
• One single document for a large system containing all the necessary
information for that system
• Hyperlinks
• A complete browsable document index
• A full text search of the entire document
[user@host ~]$ man tar
[user@host ~]$ pinfo tar
ITL CS110 Mr. Jatin Arora - G25 15
help
whoami command:
• This is another command to check who is logged in on a particular
terminal. So it will return the details of the user logged in on that
particular terminal. whoami (without spaces) shows the login name
only without other details.
user1@home:~$ whoami
root //Name of the current user
ITL CS110 Mr. Jatin Arora - G25 17
history
Command History [user@host ~]$ history
...output omitted...
• The history command displays a 23 clear
24 who
list of previously executed 25 pwd
commands prefixed with a 26 ls /etc
27 uptime
command number. 28 ls -l
• The exclamation point character 29 date
30 history
(!) is a metacharacter that is used [user@host ~]$ !ls
ls -l
to expand previous commands total 0
without having to retype them. drwxr-xr-x. 2 user user 6 Mar 29 21:16 Desktop
...output omitted...
The !number command expands [user@host ~]$ !26
to the command matching the ls /etc
abrt hosts pulse
number specified. adjtime hosts.allow purple
aliases hosts.deny qemu-ga
• The !string command expands to ...output omitted...
the most recent command that
begins with the string specified.
ITL CS110 Mr. Jatin Arora - G25 18
date
• The date command displays the current date and time. It can also be
used by the superuser to set the system clock. An argument that begins
with a plus sign (+) specifies a format string for the date command.
[user@host ~]$ date
Sat Jan 26 08:13:50 IST 2019
[user@host ~]$ date +%R
08:13
[user@host ~]$ date +%x
01/26/2019
[user@host ~]$ cal 07 2021
[user@host ~]$ cal –y # current Year
[user@host ~]$ cal -3 # prev-current-next month cal
[user@host ~]$ cal 2007 # cal of particular year
Linux
Id
The id command shows you the real and the effective user and group
IDs of a given user. Following is its syntax:
1. Which key combination would allow you to switch from the GUI to the text virtual terminal
4?
a) CTRL-SHIFT-F4
b) CTRL-ALT-SHIFT-SUPER-F4
c) CTRL-ALT-F4
d) CTRL-SHIFT-F4
2. Assuming you are the root user, which commands allow you to shut down your
system without rebooting?
a) a) shutdown -r now
b) b) halt
c) c) poweroff
d) d) shutdown -h now
3. Command used to check the boot time of Machine
who –b
who –boot who –c boot
Shortcut Description
Ctrl+A Jump to the beginning of the command line.
Ctrl+E Jump to the end of the command line.
Ctrl+U Clear from the cursor to the beginning of the command
line.
Ctrl+K Clear from the cursor to the end of the command line.
When we install the Linux operating system, Linux offers many file
systems such as Ext, Ext2, Ext3, Ext4, JFS, ReiserFS, XFS,
btrfs, and swap.
The file system Ext stands for Extended File System. It was primarily
developed for MINIX OS. The Ext file system is an older version, and is
no longer used due to some limitations.
Ext2 is the first Linux file system that allows managing two terabytes of
data. Ext3 is developed through Ext2; it is an upgraded version of Ext2 and
contains backward compatibility. The major drawback of Ext3 is that it
does not support servers because this file system does not support file
recovery and disk snapshot.
Ext4 file system is the faster file system among all the Ext file systems. It is
a very compatible option for the SSD (solid-state drive) disks, and it is the
default file system in Linux distribution.
When navigating the Linux file system you are sure to encounter
different file types. The most used and obvious file types are regular
files and directories. However, the Linux operating system has more
to offer in terms of file types as it also includes another 5 file types.
There is only one command you need to know, which will help you to
identify and categorize all the seven different file types found on the Linux
system.
ls -l | grep ^-
ls command will show the file type as an encoded symbol found as the
first character of the file permission part. In this case it is "-", which
means "regular file".
The regular file is a most common file type found on the Linux system. It
governs all different files such us text files, images, binary files, shared
libraries, etc. You can create a regular file with the touch command:
$ touch linux.com
$ ls -ld linux.com
-rw-rw-r-- 1 lubos lubos 0 Jan 10 12:52 linux.com
Directory is second most common file type found in Linux. Directory can
be created with the mkdir command:
$ mkdir FileTypes
$ ls -ld FileTypes/
drwxrwxr-x 2 lubos lubos 4096 Jan 10 13:14 FileTypes/
Character and block device files allow users and programs to communicate
with hardware peripheral devices. For example:
$ ls -ld /dev/vmmon
crw------- 1 root root 10, 165 Jan 4 10:13 /dev/vmmon
Block devices are similar to character devices. They mostly govern hardware
as hard drives, memory, etc.
$ ls -ld /dev/sda
brw-rw---- 1 root disk 8, 0 Jan 4 10:12 /dev/sda
$ ln -s source.file softlink.file
Dated: 7/16/2021
1. cat-concatenate
2. cp-copy
3. mv-move
4. rm-remove
5. ls-list
6. touch
7. which is
8. where is
9. what is
Open up a terminal:
The “prompt”
• Open up a terminal:
The host
Please note that the output redirection operator (>) that we've used in this case
flushes the destination file before the content is moved to it. So, it's worth
knowing that there exists another redirection operator (>>) that just appends the
contents to the destination file, instead of flushing it first.
6. Cat command can display content in reverse order using tac command.
Command:
$tac filename
Syntax:
cp [OPTION] Source Destination Directory
cp [OPTION] Source Directory Destination Directory
cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory
First and second syntax is used to copy Source file to Destination file
or Directory.
Third syntax is used to copy multiple Sources(files) to Directory.
cp command options
cp command main options:
option description
cp -R
recursive copy (including hidden files)
OR r
Update all files in current directory - copy only newer files to destination
directory bak:
$ cp -u * bak
mv command syntax
$ mv [options] source dest
mv command options
mv command main options:
option description
$mv file1 file2 #Rename the file file1 in the current directory to file2
$mv file1 dir2 #Move the file file1 to the directory dir2
Rename the file "My file.txt" to "My file 2.txt". Here, the spaces in the file
name are escaped, protecting them from being interpreted as part of the
command.
mv "My file.txt" "My file 2.txt"
rm Options
Option Description
rm -r mydirectory
Remove the directory mydirectory, and any files and directories it contains. If a file or
directory that rm tries to delete is write-protected, you will be prompted to make sure
that you really want to delete it.
rm -rf mydirectory
Same as the above command, but you will never be prompted; if rm can delete the files,
it will.
For example
$ rm file1 #The current directoryfile1File delete, need to confirm before deleting,
confirm delete inputy
$ rm -rf /mnt/test #Will/mnt/test The directory and the files in the directory are deleted
without confirmation
ls -a In Linux, hidden files start with . (dot) symbol and they are not visible in
the regular directory. The (ls -a) command will enlist the whole list of the
current directory including the hidden files.
ls -l It will show the list in a long list format.
ls -lh This command will show you the file sizes in human readable format. Size
of the file is very difficult to read when displayed in terms of byte. The (ls -
lh)command will give you the data in terms of Mb, Gb, Tb, etc.
ls -lhS If you want to display your files in descending order (highest at the top)
according to their size, then you can use (ls -lhS) command.
ls -l - -block-size=[SIZE] It is used to display the files in a specific size format. Here, in [SIZE] you
can assign size according to your requirement.
ls -g or ls -lG With this you can exclude column of group information and owner.
ls -li This command prints the index number if file is in the first column.
ls -p It is used to identify the directory easily by marking the directories with a slash
(/) line sign.
ls -lX It will group the files with same extensions together in the list.
ls -lt It will sort the list by displaying recently modified filed at top.
In Linux every single file is associated with timestamps, and every file
stores the information of last access time, last modification time and last
change time. So, whenever we create new file, access or modify an
existing file, the timestamps of that file automatically updated.
Which command is very small and simple command to locate executables in the system.
whatis command in Linux is used to get a one-line manual page descriptions. In Linux, each
manual page has some sort of description within it. So this command search for the manual
pages names and show the manual page description of the specified filename or argument.
1. cd
2. pwd
3. mkdir
4. rmdir
Directory Description
Command
pwd The pwd command stands for (present working directory). It displays the
current working location or directory of the user. It displays the whole
working path starting with /. It is a built-in command.
ls The ls command is used to show the list of a folder. It will list out all the
files in the directed folder.
cd The cd command stands for (change directory). It is used to change to the
directory you want to work from the present directory.
mkdir With mkdir command you can create your own directory.
rmdir The rmdir command is used to remove a directory from your system.
cd [OPTIONS] directory
By default, when you log into your Linux system, your current working directory is set to your
home directory. Assuming that the Downloads directory exists in your home directory, you can
navigate to it by using the relative path to the directory:
You can also navigate to the same directory by using its absolute path:
cd /home/username/Downloads
In short, if the path starts with a slash (/), it is the absolute path to the directory.
Suppose you are currently in the /usr/local/share directory. To switch to the /usr/local
directory (one level up from the current directory), you would type:
cd ../
To move two levels up to the /usr directory (the parent’s parent), you could run the
following:
cd ../../
Here is another example. Let’s say you are in the /usr/local/share directory, and you
want to switch to the /usr/local/src. You can do that by typing:
cd ../src
cd ~
For example, if you want to navigate to the Downloads directory, which is inside your
home directory, you would type:
cd ~/Downloads
You can also navigate to another user’s home directory using the following syntax:
cd ~username
pwd
This command displays the present working directory where you are
currently in.
$ pwd
/home/yusufshakeel
mkdir command in Linux allows the user to create directories (also referred to as folders
in some operating systems ). This command can create multiple directories at once as
well as set the permissions for the directories. It is important to note that the user
executing this command must have enough permissions to create a directory in the
parent directory, or he/she may recieve a ‘permission denied’ error.
Syntax:
mkdir
This command will create a new directory, provided it doesn't exists.
$ mkdir example
mkdir -p
This command will create nested directories.
In the following example we are creating world directory which is inside the hello
directory which is inside the example directory.
$ mkdir -p example/hello/world
rmdir command is used remove empty directories from the filesystem in Linux. The rmdir command removes
each and every directory specified in the command line only if these directories are empty. So if the specified
directory has some directories or files in it then this cannot be removed by rmdir command.
The syntax of rmdir command is as follows:
$ rmdir ~/Documents/myfiles
This command will remove the “myfiles” directory located in the “~/Documents” path only if it is empty. If the
directory is not empty, the command will fail and displays the “Directory not empty” message.
To remove the “docs” directory along with its parent directories “myfiles” and “files”, use the -
p command as follows:
Dated: 20-07-2021
The block device specifies the physical device or the CD-ROM is attached to. On
most Linux systems, you can use /dev/cdrom, which would be a symbolic link to
something like /dev/hdc for an ATAPI CD-ROM, selected as a master device, on the
secondary IDE
# mount -t iso9660 -o ro /dev/cdrom /mnt/cdrom
Note- only the root superuser can run this version of the mount command, so you
need to log in as root to do this. For the safety and security of your own computer,
you should log out as soon as you have entered this command successfully.
Practice Questions
Dated: 22-07-2021
1. To display Manual
# man diff
2. To compare file using diff command
diff file1 file2
outpu :$cmp file1.txt file2.txt file1.txt file2.txt differ: byte 9, line 2 /*indicating that
the first mismatch found in two files at byte 20 in second line*/
Jatin Arora Introduction to Linux G25
Options of cmp
2. -i [bytes-to-be-skipped] :
$cmp -i 10 file1.txt file2.txt $
Output: indicating that both files are identical after 10 bytes skipped from
both the files.
• 4. -l option : This option makes the cmp command print byte position and byte value
for all differing bytes.
• Output $cmp -l file1.txt file2.txt 20 12 56 21 124 12 22 150 124 23 151 150 24 163
151 25 40 163 26 146 40 27 150 151 28 12 24 29 124 145 30 157 163
• /*indicating that files are different displaying the position of differing bytes along with the
differing bytes in both file*/ The first column in the output represents the position (byte
number) of differing bytes. The second column represents the byte value of the differing
byte in the first file, while the third column represents the byte value of the differing byte
in the second file.
• /*indicating files are different without displaying the differing byte and line*/
• comm compare two sorted files line by line and write to standard output; the
lines that are common and the lines that are unique.
Questions
1. Create a file by your section name having name of all the students of
your section,
2. create another file by your subsection name having name of ll the
students in your subsection.
3. Compare the two files using all the comparison commands
Dated: 05-07-2021
The bz2 feature compresses and creates an archive file less than the size of
the gzip. The bz2 compression takes more time to compress and decompress files
than gzip, which takes less time. To create a highly compressed tar file we use the
option j.
# tar cvfj demo.tar.bz2
OR
# tar cvfj demo.tar.tbz
OR
# tar cvfj demo.tar.tb2
12. Untar Multiple files from tar, tar.gz, and tar.bz2 File
To extract or untar multiple files from the tar, tar.gz, and tar.bz2 archive file. For example,
the below command will extract “file 1” “file 2” from the archive files.
Example:
$ gzip mydoc.txt
This command will create a compressed file of mydoc.txt named as mydoc.txt.gz and
delete the original file.
-f option : Sometimes a file cannot be compressed. Perhaps you are trying to compress a
file called “myfile1” but there is already a file called “myfile1.gz”. In this instance, the “gzip”
command won’t ordinarily work.
To force the “gzip” command to do its stuff simply use -f option: $ gzip -f myfile1.txt
This will forcefully compress a file named myfile.txt even if there already exists a file named
as myfile.txt.gz
$ gzip -9 mydoc.txt
To get minimum compression at the fastest speed
-v option: This option displays the name and percentage reduction for each file
compressed or decompressed.
$ gzip -v mydoc.txt
OUTPUT :
new.txt: 18.2% -- replaced with new.txt.gz
-d option :This option allows to decompress a file using the “gzip” command.
$ gzip -d mydoc.txt.gz
QUESTIONS
1. What is the zcat command used for?
2. What do you mean by archiving?
3. Give commands for uncompressing a file?
4. What is the purpose for gzip command?
5. What are .tar files?
6. What are .Z files?
7. What extensions are given to the compressed files?
8. Why do you need to compress the files?
Editors in Linux
• Gedit
• Vi
• Vim
Line • Type : to switch to the Line mode from Command mode. Each key is
an external command, including operations such as writing the file
contents to disk or exiting.
• Uses line editing commands inherited from older line editors. Most of
these commands are actually no longer used. Some line editing
commands are very powerful.
• Press Esc to exit Line mode and return to Command mode.
Dr. Jatin Arora ITL CS110 - G25 13
Command Mode
The table describes the most important commands used to start, exit, read, and
write files in vi. The ENTER key needs to be pressed after all of these commands
Command Usage
vi myfile Start the vi editor and edit the myfile file
vi -r myfile Start vi and edit myfile in recovery mode from a system
crash
:r file2 Read in file2 and insert at current position
:w Write to the file
:w myfile Write out the file to myfile
:w! file2 Overwrite file2
:x or :wq Exit vi and write out modified file
:q Quit vi
:q! Quit vi even though modifications have not been saved
Key Usage
o Start a new line below current line, insert text there; stop upon Escape key
O Start a new line above current line, insert text there; stop upon Escape key
R Replace text starting with current position; stop upon Escape key
Command Usage
/pattern Search forward for pattern
?pattern Search backward for pattern
The table describes the most important keystrokes used when searching for text in vi.
Key Usage
n Move to next occurrence of search pattern
N Move to previous occurrence of search
pattern
1. Wildcards (Globbing)
2. Find Command
3. Locate Command
4. Q/A
5. Activity based on Searching.
Pattern Matching
Globbing is a shell command-parsing operation that expands a wildcard
pattern into a list of matching path names. Command-line metacharacters are
replaced by the match list prior to command execution. Patterns that do not
return matches display the original pattern request as literal text.
Pattern Matches
* Any string of zero or more characters.
? Any single character.
[abc...] Any one character in the enclosed class (between the square brackets).
[!abc...] Any one character not in the enclosed class.
[^abc...] Any one character not in the enclosed class.
[[:alpha:]] Any alphabetic character.
[[:lower:]] Any lowercase character.
[[:upper:]] Any uppercase character.
[[:alnum:]] Any alphabetic character or digit.
[[:punct:]] Any printable character not a space or alphanumeric.
[[:digit:]] Any single digit from 0 to 9.
[[:space:]] Any single white space character. This may include tabs, newlines,
carriage returns, form feeds, or spaces.
In the following example the echo command is used to display the value of
the tilde character.
The echo command can also be used to display the values of brace and
variable expansion characters, and others.
You can assign data as a value to a variable using the following syntax:
Many characters have special meaning in the Bash shell. To keep the shell from
performing shell expansions on parts of your command line, you can quote and
escape characters and strings.
The backslash (\) is an escape character in the Bash shell. It will protect the
character immediately following it from expansion.
6. Move the hello.txt file to the Desktop by using find command. Remove
3. Find is slow
• The reason locate is so fast is because it doesn't read the file system for the searched
file or directory name. It actually refers to a database (prepared by the
command updatedb) to find what user is looking for and based on that search,
produces its output.
• While this is a good approach, it has its share of drawbacks. The main issue is that after
every new file or directory is created on the system, you need to update the tool's
database for it to work correctly. Otherwise, the command will not be able to find
files/directories that are created after the last database update.
Jatin Arora Introduction to Linux G25
Locate ..
• Syntax of Locate Command is
• locate “filename”
• If you create a file touch ac.txt and then use locate ac.txt
• then it will not work. First we have to use sudo updatedb and
•List out all the files whose name start from a to z and file name can be of
•List all the files where file name does not start with a or b or c and follow any
number of characters
•List all the files those start with lowercase letter and follow any number of
characters
• List all the files those start with any digit and follow any number of characters
•List all the files those first letter is uppercase alphabet, second letter is is a
• These are the users which have been created by the Root
and has limited access to the resources and need
permission from Root to access any secure resources and
services
• Normal users have the necessary privileges to perform
standard tasks on a Linux computer such as running word
processors, databases, and Web browsers.
• They can store files in their own home directories. Since
regular users do not normally have administrative
privileges, they cannot accidentally delete critical
operating system configuration files.
• Username
• Password
• By default, all user home directories are
created and maintained in the /home
directory.
• However, the root user’s home directory is
/root
Shell This is the default shell that will be provided to the user.
Last Login This displays the last time the user logged in and
where from
Username:Password:Last_Modified:Min_Days:Max_Days:D
ays_Warn:Disabled_Days:Expire
• Username This is the user’s login name from /etc/passwd.
• Password This is the user’s password in encrypted format
• Last_Modified This field displays the number of days since January
1, 1970 that the password was last changed
• Min_Days This field displays the minimum number of days required
before a password can be changed.
• Max_Days This field displays the maximum number of days before
a password must be changed.
• Days_Warn This field displays the number of days prior to password
expiration that the user will be warned of the pending expiration..
• Using useradd
• Using passwd
• Using usermod
• Using userdel
Password User password (or the character x if the password Is never shown in Linux when it is being typed; this stops prying eyes
is stored in the /etc/shadow file) in encrypted
format
User ID (UID) Every user must have a user id (UID) •UID 0 is reserved for root user
•UID's ranging from 1-99 are reserved for other predefined accounts
•UID's ranging from 100-999 are reserved for system accounts and
groups
•Normal users have UID's of 1000 or greater
Group ID (GID) The primary Group ID (GID); Group Identification Is covered in detail in the chapter on Processes
Number stored in the /etc/group file
User Info This field is optional and allows insertion of extra For example: Rufus T. Firefly
information about the user such as their name
Home Directory The absolute path location of user's home For example: /home/rtfirefly
directory
Shell The absolute location of a user's default shell For example: /bin/bash
Ritu Rathee
Introduction to Linux CS-110 3
User’s Password File
The SHA-512 algorithm is widely used for security applications and protocols. These
security applications and protocols include TLS, SSL, PHP, SSH, S/MIME and
IPSec. SHA-512 is one of the most tested hashing algorithms.
Ritu Rathee
Introduction to Linux CS-110 4
Types of Accounts
• Root
• System
• Normal
• Network
For a safe working environment, it is advised to grant the minimum
privileges possible and necessary to accounts, and remove inactive
accounts. The last utility, which shows the last time each user logged
into the system, can be used to help identify potentially inactive
accounts which are candidates for system removal.
Ritu Rathee
Introduction to Linux CS-110 5
Understanding the root Account
• root is the most privileged account on a Linux/UNIX system. This account has the
ability to carry out all facets of system administration, including adding accounts,
changing user passwords, examining log files, installing software, etc. Utmost care
must be taken when using this account. It has no security restrictions imposed upon
it.
• When you are signed in as, or acting as root, the shell prompt displays '#' (if you
are using bash and you haven’t customized the prompt as we discuss elsewhere in
this course). This convention is intended to serve as a warning to you of the
absolute power of this account.
Operations that require root Privileges
Ritu Rathee
Introduction to Linux CS-110 6
Creating a New User Account
3. Enter the password and press the ENTER key. To confirm the password,
the prompt Retype new password: is displayed.
4. Enter the password again and press the ENTER key.
The message passwd: all authentication tokens updated successfully. is
displayed.
Ritu Rathee
Introduction to Linux CS-110 7
Comparing su and sudo
su sudo
1 When elevating privilege, you need When elevating privilege, you need to enter the
to enter the root password. user’s password and not the root password.
2 Once a user elevates to the root Offers more features and is considered more
account using su, the user can do secure and more configurable.
anything that the root user can do.
3 The command has limited logging The command has detailed logging features.
features
sudo has the ability to keep track of unsuccessful attempts at gaining root
access. Users' authorization for using sudo is based on configuration
information stored in the /etc/sudoers file and in
the /etc/sudoers.d directory.
A message such as the following would appear in a system log file
(usually /var/log/secure) when trying to execute sudo bash without
successfully authenticating the user:
Ritu Rathee
Introduction to Linux CS-110 8
sudoers File
Ritu Rathee
Introduction to Linux CS-110 9
Sudo logging
Ritu Rathee
Introduction to Linux CS-110 10
MulTi-Tasking and MulTi-User
System
Ritu Rathee
Introduction to Linux CS-110 11
Permissions
Ritu Rathee
Introduction to Linux CS-110 12
chmod
Ritu Rathee
Introduction to Linux CS-110 13
File Permissions
Value Meaning
777 rwxrwxrwx
755 rwxr-xr-x
700 rwx------
666 rw-rw-rw-
644 rw-r--r--
600 rw-------
Ritu Rathee
Introduction to Linux CS-110 14
If we wanted to set some_file to have read and write permission for the
owner, but wanted to keep the file private from others, we would:
Ritu Rathee
Introduction to Linux CS-110 15
Directory permissions
777 rwxrwxrwx
755 rwxr-xr-x
700 rwx------
Ritu Rathee
Introduction to Linux CS-110 16
File permissions
To see the permission settings for a file, we can use the ls command as
follows:
[me@linuxbox me]$ ls -l some_file
-rw-rw-r-- 1 me we 1097374 Apr 27 18:48 some_file
Ritu Rathee
Introduction to Linux CS-110 17
• Let's try another example. We will look at the bash program which
is located in the /bin directory:
• su
[me@linuxbox me]$ su
Password:
[root@linuxbox me]#
sudo
[me@linuxbox me]$ sudo some_command Password: [me@linuxbox
me]$
Ritu Rathee
Introduction to Linux CS-110 20
Chgrp and Chown
Ritu Rathee
Introduction to Linux CS-110 21
Activity
• Create a new user, using useradd, and give the user an initial password
with passwd.
• Configure this user to be able to use sudo.
• Login as or switch to this new user and make sure you can execute a
command that requires root privilege.
• For example, a trivial command requiring root privilege could be:
$ ls /root
• Click the link below to view a solution to the Lab exercise.
Ritu Rathee
Introduction to Linux CS-110 22
Activity Solution
Ritu Rathee
Introduction to Linux CS-110 23
Questions
Ritu Rathee
Introduction to Linux CS-110 24
rea
Ritu Rathee
Introduction to Linux CS-110 25
Introduction to Linux (CS-110) Class
On
Filters in Linux
Note: If there is an existing file with the same name, the redirected command
will delete the contents of that file and then it may be overwritten."
If you do not want a file to be overwritten but want to add more content to an
existing file, then you should use '>>' operator.
• The most useful and powerful thing you can do with I/O redirection is
to connect multiple commands together with what are called pipelines.
With pipelines, the standard output of one command is fed into the
standard input of another.
linux is my life
linux has changed my life
linux is best and everthing to me..:)
LINUX IS MY LIFE
LINUX HAS CHANGED MY LIFE
LINUX IS BEST AND EVERTHING TO ME..:)
cat linux.txt | tr [a-z] [A-Z]
cat domains.txt | tr -d '‘ # Remove the spaces
Using Styles ( -b )
• There are three output styles to choose from:
• a = Number all lines
• t = Number only nonempty lines
• n = Number no Lines
• p = Number only lines that contain a match for the basic regular expression
[savona@putor tmp]$ nl -ba test
1 This is a test file
2
3
4 Above are some blank lines
5
6
7 Maybe they will will be numbered, maybe not.
8 This is the end. Beautiful friend, the end.
In this lecture we’ll often refer to the file emp.lst. Let’s take a close look at the file and
understand the organization:
grep scans its input for a pat- tern, and can display the selected pattern, the line
numbers, or the filenames where the pattern occurs. The command uses the
following syntax:
grep searches for pattern in one or more filename(s), or the standard input if no
filename is specified. The first argument (barring the option) is the pattern, and
the ones remain- ing are filenames. Let’s use grep to display lines containing the
string sales from the sample database, emp.lst:
When grep is used with multiple filenames, it displays the filenames along with the
output. In the next example, grep searches two files. Don’t bother about what they
contain; just observe how each line is preceded by the filename:
Quote the pattern used with grep if it contains multiple words or special characters that can be
interpreted otherwise by the shell. You can generally use either single or double quotes. However,
if the special characters in the pattern require command substitution or variable evaluation to be
performed, you must use double quotes.
The command failed because the string president couldn’t be located. Though the feature of scanning
a file for a pattern is available in both sed and awk, these commands are not considered to fail if
they can’t locate a pattern. find also doesn’t fail if no file is found.
Don’t, however, draw the wrong conclusion from the preceding behavioral pattern of grep. The
silent return of the shell prompt is no evidence of failure. In fact, the silent behavior of cmp denotes
success. Success or failure is denoted by the exit status (7.5) that is stored in a special variable ($?)
when a command has finished execution. The if conditional and while loop test this exit status to
control the flow of execution.
Deleting Lines (-v) grep can also play an inverse role; the -v (inverse) option selects all lines except
those containing the pattern. Thus, you can create a file otherlist containing all but directors:
More often than not, when we use grep -v, we also redirect its output to a file as a means of getting
rid of unwanted lines. Obviously, the lines haven’t been deleted from the original file as such.
The -v option removes lines from grep’s output, but it doesn’t actually change the argument file.
This option is frequently used with redirection.
Introduction to Linux Dr. Poonam Panwar G32, G33
Displaying Filenames (-l)
Programmers often use the -l (list) option to locate files where a variable or system call has been
used. You can easily find out the C programs that use the fork system call:
Assuming that the pattern can occur multiple times in a file, can you sort this file list in order of their
modification or access time?
The -e option has two functions—to match multiple patterns and patterns beginning with a hyphen.
Linux supports both functions, but Solaris offers this option only with the XPG4 version. This is
how you match multiple patterns by using -e multiple times:
grep supports sophisticated pattern matching techniques that can display the same lines but with a
single expression. This is the ideal forum for regular expressions to make their entry.
Extended regular expressions (ERE) make it possible to match dissimilar patterns with a single
expression. This set uses some additional characters and POSIX-compliant versions of grep use them
with the -E option. Linux grep supports this option, but Solaris users must use /usr/xpg4/bin/grep to
use EREs. If your version of grep doesn’t support this option, then use egrep but without the -E
option.
Fgrep or the Fixed grep or grep -F is yet another version of grep which is fast in searching when it
comes to search for the entire string instead of regular expression as it doesn‘t recognize the regular
expressions, neither any meta-characters. For searching any direct string, this is the version of grep
which should be selected.
Fgrep searches for complete string and doesn‘t even recognize special characters as part of regular
expression even if escaped or not escaped. Options used in grep are also can be used with fgrep.
sed is a multipurpose tool that combines the work of several filters. It is derived from ed, the original
UNIX editor (not discussed in this text). sed performs noninteractive operations on a data
stream—hence its name. It uses very few options but has a host of features that allow you to select
lines and run instructions on them. Learning sed will prepare you well for perl, which uses many of
these features.
sed uses instructions to act on text. An instruction combines an address for selecting lines, with an
action to be taken on them, as shown by the syntax:
sed options ‘address action’ file(s)
This form of addressing lets you specify a pattern (or two) rather than line numbers. This is known
as context addressing where the pattern has a / on either side.
Searching a pattern:
Substitution is easily the most important feature of sed, and this is one job that sed does
exceedingly well. It lets you replace a pattern in its input with something else. The use of regular
expressions enhances our pattern matching capabilities, and in this chapter we feature some more
regular expression characters that make the use of sed so compelling.
Though we see two lines here, the substitution has been carried out for the entire file. Also,
sed ‘1,3s/:/|/g’ emp.lst First three lines only And you can remove the source string altogether by using
two /s:
When a g is used at the end of a substitution instruction, the change is performed globally
along the line. Without it, only the leftmost occurrence is replaced.
1. Write a command to print the lines that has the the pattern "july" in all the files in a
particular directory?
2. Write a command to select only those lines containing "july" as a whole word?
1. Process
2. Shell and init
3. ps
4. Top
5. kill
6. killall
• The Process-id (PID) Each process is identified by a unique integer called the
Process-id (PID).
• The Parent PID (PPID) When several processes have the same PPID, it often makes
sense to kill the parent rather than all of its children separately.
When you log in, the process representing the shell starts running at your terminal. This
process may be sh, ksh, csh, or bash. The shell maintains a set of environment variables,
and you have already encountered some of them like PATH and HOME. The shell’s own
pathname is stored in SHELL, but its PID is stored in a special “variable”, $$. To know the
PID of your current shell, type
The PID of your login shell obviously can’t change as long as you are logged in. When you
log out and log in again, your login shell will be assigned a different PID. Knowledge of the
PID is often necessary to control the activities at your terminal, especially when things go
wrong.
By default, ps displays the processes owned by the user invoking the command:
$ ps
ps presents a snapshot of the process table. This picture gets outdated by the time it is
displayed. On some systems, you might see ps itself in the output. ps is a highly variant
command; its actual output varies across different LINUX flavors.
Since knowing the parentage is often important, the -f option displays a fuller listing that
includes the PPID:
$ ps -f
System processes that have no controlling terminal are easily identified by the ? in the
TTY column. A process that is disassociated from the terminal can neither write to the
terminal nor read from it. You can’t press [Ctrl-c] to interrupt the process either. Such
processes are also known as daemons. Many of these daemons are actually sleep- ing (a
process state) and wake up only when they receive input.
$ ps f U sumit
PID TTY
936 pts/0 14833 pts/0
STAT TIME COMMAND
S 0:00 \_ /bin/bash
S 0:00 | \_ vim yrunix07
938 pts/2 S 14835 pts/2 R 945 pts/4 S 14831 pts/4 S 1047 ? S 14579 ? S
0:00 \_ /bin/bash
0:00 | \_psf-usumit 0:00 \_ /bin/bash
0:00 \_ rlogin arka
22:08 /usr/lib/mozilla-1.0.1/mozilla-bin
0:22 | | \_ /usr/lib/acroread/Reader/intellinux/bin/a
A typical Linux system shows a host of system processes, but Linux uses the ax option to
display them. Here’s a vastly censored display:
• Exec Forking creates a process, but it is not enough to run a new program. To do that,
the forked child needs to overwrite its own image with the code and data of the new
program.
• Wait While the child is executing a new program, the parent normally waits for the child
to die. It then picks up the exit status of the child (explained shortly) before it does
something else.
terminates the job having PID 105. To facilitate premature termination, the & operator
(7.10.1) displays the PID of the process that’s run in the background. If you don’t re-
member the PID, use the ps command to find out and then use kill.
If all of these processes have the same parent, you may simply kill the parent to kill all its
children. However, when you use nohup (7.10.2) with a set of commands and log out, you
can’t kill the parent as init acquires their parentage. You then have to kill the processes
individually because you can’t kill init.
General Syntax:
killall [ -Z CONTEXT ] [ -u USER ] [ -y TIME ] [ -o TIME ] [ -eIgiqrvw ]
• Create a job that writes the date to an output file thrice, with a gap of 60 seconds and
180 seconds. Check whether the job is running and bring it to foreground job. Stop the
foreground job and make it run in the background. Finally, kill the background job and
verify its status.
1. Process Scheduling
2. at
3. batch
4. Cron
5. Running jobs in background
6. No Logging Out
7. Nohup
8. Process Priority
Linux provides sophisticated facilities to schedule a job to run at a specified time of day. If the
system load varies greatly throughout the day, it makes sense to schedule less urgent jobs at a time
when the system overheads are low. The at and batch commands make such scheduling possible.
• Besides specifying the time to run the job, you can also include a specific date, using a few different
date formats:
• A standard date format, such as MMDDYY, MM/DD/YY, or DD.MM.YY
• A text date, such as Jul 4 or Dec 25, with or without the year
• You can also specify a time increment:
■ Now + 25 minutes
■ 10:15PM tomorrow
■ 10:15 + 7 days
The atq command allows you to view what jobs are pending on the system:
$ at -f test5 10:15
warning: commands will be executed using /bin/sh job 7 at 2007-11-04 10:15
$ at -f test5 4PM
warning: commands will be executed using /bin/sh job 8 at 2007-11-03 16:00
$ at -f test5 1PM tomorrow
warning: commands will be executed using /bin/sh job 9 at 2007-11-04 13:00
$ atq
7 2007-11-04 10:15 a
8 2007-11-03 16:00 a
9 2007-11-04 13:00 a
$
The job listing shows the job number, the date and time the system will run the job, and the job
queue the job is stored in.
• The batch command is a little different from the at command. Instead of scheduling a script to
run at a preset time, you use the batch command to schedule a script to run when the system is at
a lower usage level. This is a great feature for servers that may experience different load levels at
various times of the day and night.
• The batch command checks the current load average of the Linux system. If the load average is
below 0.8, it runs any jobs waiting in the job queue.
• The command format for the batch command is:
batch [-f filename] [time]
• Similarly to the at command, by default the batch command reads commands from STDIN. You
can use the -f parameter to specify a file to read commands from. You can also optionally specify
the earliest time that the batch command should try running the job.
• Not all users may be able to use the at and batch commands. The access to these com- mands is
restricted and controlled by the files at.allow and at.deny. The locations are system-dependent; look up
the FILES section of the man page of at for the location of the files. If they exist at all, they could be in
/etc, /etc/cron.d or /usr/lib/cron. They can only be edited by the superuser.
• at.allow controls the primary level of security. If it is present, only the users listed in the file are
permitted to use at and batch. If it is not present, the system checks at.deny for a list of users who are
barred from using these commands. If neither file is present, only the system administrator is permitted
to invoke at and batch.
• The cron table uses a special format for allowing you to specify when a job should be run. The
format for the cron table is:
min hour dayofmonth month dayofweek command
• The cron table allows you to specify entries as specific values, ranges of values (such as 1–5) or as
a wildcard character (the asterisk). For example, if you want to run a command at 10:15 on every
day, you would use the cron table entry of:
15 10 * * * command
• The wildcard character used in the dayofmonth, month, and dayofweek fields indicates that cron
will execute the command every day of every month at 10:15. To specify a command to run at
4:15PM every Monday, you would use:
15 16 * * 1 command
• You can specify the day of week entry as either a three-character text value (mon, tue, wed, thu,
fri, sat, sun) or as a numeric value, with 0 being Sunday and 6 being Saturday.
Each system user can have their own cron table (including the root user) for running scheduled jobs.
Linux provides the crontab command for handling the cron table. To list an existing cron table, use the
-l parameter:
$ crontab -l
no crontab for rich
$
By default, each user’s cron table file doesn’t exist. To add entries to your cron table, use the -e
parameter.
crontab foo
to place the entry in the directory /var/spool/cron/crontabs. You can see the contents
of your crontab file with crontab -l and remove it with
crontab -r.
If you use crontab - to provide input through the standard input and then decide to abort it, you
should terminate it with the interrupt key applicable to your terminal, rather than [Ctrl-d]. If you
forget to do that, you’ll remove all entries from your existing crontab file!
• anacron cron assumes that the machine is run continuously, so if the machine is not up when a job is
scheduled to run, cron makes no amends for the missed op- portunity. The job will have to wait for its
next scheduled run. The anacron com- mand is often more suitable than cron. anacron periodically
inspects its control file (/etc/anacrontab) to see if there’s a job which has “missed the bus.” If it finds
one, it executes the job.
ls -l
total 8
-rwxr--r-- 1 rich rich 219 Nov 2 11:27 test1* $ Loop #3
When you place the ampersand symbol after a command it separates the command from the bash shell and
runs it as a separate background process on the system. The first thing that displays is the line:
[1] 19555
The number in the square brackets is the job number assigned to the background process by the shell. The
next number is the PID the Linux system assigns to the process. Every process running on the Linux system
must have a unique PID.
You can start any number of background jobs at the same time from the command line prompt:
The shell died on logging out but its child (sort) didn’t; it turned into an orphan.
Unlike the &, which needs to be affixed only to the end of the command line, nohup needs to be used
with each command in a pipeline:
nohup grep ‘director’ emp.lst & | nohup sort &
• In a multitasking operating system (which Linux is), the kernel is responsible for assigning CPU time
for each process running on the system. Only one process at a time can actually be running in the CPU,
so the kernel assigns CPU time to each process in turn.
• By default, all processes started from the shell have the same scheduling priority on the Linux system.
The scheduling priority is the amount of CPU time the kernel assigns to the process relative to the other
processes.
• The scheduling priority is an integer value, from −20 (the highest priority) to +20 (the lowest priority).
By default, the bash shell starts all processes with a priority of 0.
• This means that a simple script that only requires a little bit of processing time gets the same CPU time
slices as a complex mathematical algorithm that can take hours to run.
• Sometimes you want to change the priority of a specific command, either lowering its priority so that it
doesn’t take as much processing power from the CPU or giving it a higher priority so that it gets more
processing time. You can do this by using the nice command.
If you want to fully control running processes, you must be logged in as the root account.
From the sample top output below, the niceness of the teamspe+ with PID 1055 is now -12 and for all
processes owned by user apache is -2.
• Create job using at to back up files in one directory to another 10 minutes from now.
• Set up a cron job to backup the files in one directory to another every day at 10 am. Put the
commands in file called mycron.
• A user can change their own shell to any thing: which, however must be
listed in the /etc/shells file.
• Only root can run a shell not listed in /etc/shells file.
• If an account has a restricted login shell, then only root can change that
user’s shell.
usermod --shell /bin/bash username
chsh --shell /bin/sh username
vi /etc/passwd
and press ENTER and CTRL-D to save the file, or just create hello.sh in
your favorite text editor. Then, type chmod +x hello.sh to make the file
executable by all users.
$ ./hello.sh or $ bash hello.sh
Hello Linux Foundation Student
• Note if you use the second form, you do not have to make the file
executable.
unset variable_name
Display all the System variable by running the command:env
# cat script.sh
#!/bin/bash
# Script to check the alias output
alias ls1='ls -lrt'
ls1
Ms. Ritu Rathee
Introduction to Linux CS110 - G25 16
Alias Example
• alias name="value“
• unalias [alias name]
• -p option : This option prints all the defined aliases is resuable
format.Syntax:
alias –p
• alias CD="cd Desktop"
if <CONDITION>; then
<STATEMENT>
...
<STATEMENT>
else
<STATEMENT>
...
<STATEMENT>
fi
Lastly, the if/then/else construct can be further expanded to test more than one
condition, executing a different set of actions when a condition is met. The construct
for this is shown in the following example:
if <CONDITION>; then
<STATEMENT>
...
<STATEMENT>
elif <CONDITION>; then
<STATEMENT>
...
<STATEMENT>
else
<STATEMENT>
...
<STATEMENT>
fi
Ms. Ritu Rathee
Introduction to Linux CS110 - G25 30
Case
The case statement saves going through a whole set of if .. then ..
else statements. Its syntax is really quite simple:
#!/bin/sh
echo "Please talk to me ..."
while :
do
read INPUT_STRING
case $INPUT_STRING in
hello)
echo "Hello yourself!"
;;
bye)
echo "See you again!"
break
;;
*)
echo "Sorry, I don't understand"
;;
esac
done
Ms. Ritu Rathee
Introduction to Linux CS110 - G25 31
Using Loops to Iterate Commands
System administrators often encounter repetitive tasks in their day-to-day
activities. Repetitive tasks can take the form of executing an action
multiple times on a target, such as checking a process every minute for 10
minutes to see if it has completed. Task repetition can also take the form of
executing an action once across multiple targets, such as backing up each
database on a system. The for loop is one of the multiple shell looping
constructs offered by Bash, and can be used for task iterations.
test -f filename
[ -f filename ]
-b FILE FILE exists and is block special
-c FILE FILE exists and is character special
-d FILE FILE exists and is a directory
-e FILE FILE exists
-f FILE FILE exists and is a regular file
-g FILE FILE exists and is set-group-ID
-G FILE FILE exists and is owned by the effective group ID
-h FILE FILE exists and is a symbolic link (same as -L)
-k FILE FILE exists and has its sticky bit set
Operator Meaning
[[ string1 > string2 ]] Compares the sorting order of string1 and string2.
Dated:
Department of Computer Science and
Engineering,
Chitkara University, Punjab
Command Line Arguments in Linux Shell Scripting
While running a command, the user can pass a variable number of parameters
in the command line.
Within the command script, the passed parameters are accessible using
‘positional parameters’. These range from $0 to $9, where $0 refers to the
name of the command itself, and $1 to $9 are the first through to the ninth
parameter, depending on how many parameters were actually passed.
Example:
$ sh hello how to do you do
Here $0 would be assigned sh
$1 would be assigned hello
$2 would be assigned how
And so on …
We will now look at some additional
commands to process these parameters.
Command line arguments cont…
Command line arguments cont…
Command line arguments cont…
• Go to default shell/Terminal
• vi myScript.sh
• vi editor will get opened with file name myScript.sh
• Write the script
• Press -> Escape : wq (to save and exit)
• Execute the programme by typing
□ chmod x ger.sh
□ ./ger.sh
Print all Arguments with script name and
total number of arguments passed in it
Command line arguments: Suppose you are in your home directory which
has sub-directories dir-1, dir-2, dir-3, dir-4 and dir-5. Write a shell script
which uses touch command in it to create files file-i in dir-i for i taking values
from 1 to 5 using command line arguments.
Dated:
Department of Computer Science and
Engineering,
Chitkara University, Punjab
Shell script is just a simple text file with “.sh” extension, having executable
permission.
1
Process of writing and executing a script
Open terminal. Navigate to the place where you want to create script
using ‘cd‘ command.
2 touch hello.sh (Here we named the script as hello, remember the ‘.sh‘
extension is compulsory).
3 vi hello.sh (gedit hello.sh) [You can use your favourite editor, to edit the
script]. chmod 777 hello.sh (making the script executable).
4 bash hello.sh or ./hello.sh (running the script)
"Double Quotes" - Anything enclose in double quotes remove meaning of that characters
(except \ and $).
Double
"
Quotes eg a=10
echo “Value of a is $a”
output is Value of a is 10
'Single quotes' - Single quotes won’t interpolate anything
$ n=6/3
$ echo $n
6/3
$ declare -i n
$ n=6/3
$ echo $n
2
When you do not need the declare statement is when you will use a
When
program or you do not
built-in command needa math
to evaluate the declare statement is when you w
statement.
command to evaluate a math statement.
2. expr
• An old Unix program that can evaluate math is expr. expr became popular in the days
of the Bourne Shell, which did not support math. With Bash and Korn shell, it is
generally not needed.
• Spaces Plays important role expr 20 %3 - Remainder read as 20 mod 3 and remainder is 2.
• Need of dollar in front of variable expr 10 \* 3 - Multiplication use \* and not * since its wild
card.
$ z=5
$ z=`expr $z+1` ---- Need spaces around + sign.
$ echo $z
5+1
$ z=`expr $z + 1`
$ echo $z
6
3. let
• It is also a little picky about spaces, but it wants the opposite of what expr
wanted.
• No need of $ in front of variables to be read.
$ let z=5
$ echo $z
5
$ let z=$z+1
$ echo $z
6
$ let z=$z + 1 # --- Spaces around + sign are bad with let
-bash: let: +: syntax error: operand expected (error token is "+")
$ ((e=5))
$ echo $e
5
$ (( e = e + 3 ))
$ echo $e
8
$ (( e=e+4 )) # -- spaces or no spaces, it doesn't matter
$ echo $e
12
• What if you want to do math with floating point numbers or you have some fairly
complicated math to do?
• Neither form of let, supports floating point numbers.
• Then bc command is needed.
• But you have to treat the variables as strings.
$r=3.5
$s=`echo "$r + 2.2" | bc`
$echo $s a=10.10
5.7 b=20
$ z = `echo $z + 1 | bc` echo addition of two numbers using expr
-bash: z: command not found c=`echo $a / $b | bc -l`
# -- spaces around = sign are bad
(shell thing, not bc) echo expr sum is $c
$ z=`echo "$z + 1" | bc`
$ echo $z
8
$ z=`echo "$z+1" | bc` -- spaces don't matter with bc
$ echo $z
9
1. Arithmetic Operators
2. Relational Operators
3. Boolean Operators
4.String Operators
Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for
string values unless their value is numeric.
For example, following operators will work to check a relation between 10 and 20 as well as in between "10" and "20" but not in
between "ten" and "twenty".
Assume variable a holds 10 and variable b holds 20 then −
-z Checks if the given string operand size is zero; if it is zero [ -z $a ] is not true.
length, then it returns true.
str Checks if str is not the empty string; if it is empty, then it [ $a ] is not false.
returns false.
We have a few operators that can be used to test various properties associated with a Unix file.
Assume a variable file holds an existing file name "test" the size of which is 100 bytes and
has read, write and execute permission on −
PROGRAM
then
else
fi
A shell script to find the factorial of a number A shell script to find the factorial of a number
Using for loop Using while loop
#!/bin/bash
# A shell script to find the factorial of a number
Write a Shell program to find the largest among ‘n’ different numbers.
PROGRAM
Write a Shell program to find the sum of odd and even numbers from a
set of numbers.
Ms Sangeetha Annam
Department of Computer Science and Engineering
Chitkara University, Punjab
Ms Sangeetha Annam ITL CS110 - G27 1
Arithmetic Expansion in Bash Shell
post-decrement
x=5
-- (subtract variable 4
echo $(( x-- ))
value by 1)
x=2
** Exponentiation y=3 8
echo $(( x ** y ))
Function Description
atan2(x, y) - The arctangent of x / y, with x and y specified in radians.
cos(x) - The cosine of x, with x specified in radians.
exp(x) - The exponential of x.
int(x) - The integer part of x, truncated toward 0.
log(x) - The natural logarithm of x.
rand() - A random floating point value larger than 0 and less than 1.
sin(x) - The sine of x, with x specified in radians.
sqrt(x) - The square root of x.
srand(x) -Specify a seed value for calculating random numbers.
# Works as string
expr '10 + 30'
# Works as string
expr 10+30
#Perform the addition
expr 10 + 30
#Find out the remainder value
expr 30 % 9
#Using expr with backtick
myVal1=`expr 30 / 10`
echo $myVal1
#Using expr within command substitute
myVal2=$( expr 30 - 10 )
echo $myVal2
# Dividing 8 by 3
let "val2 = 8 / 3"
echo $val2
# Subtracting 3 from 9
let val3=9-3
echo $val3
# Applying increment
let val4=7
let val4++
echo $val4
• Create a bash file and add the following code to check the use
of ‘bc’ command in arithmetic operations.
#!/bin/bash
Q2. Which expression use the value of the enclosed arithmetic expression?
a. $(())
b. $()
c. ${}
d. $[]
a. 10
b. 0
c. 1
d. None of the above