0 ratings 0% found this document useful (0 votes) 14 views 29 pages Linux Unit 4
Chapter 6 discusses securing files in Linux through file access permissions (FAPs), which manage user access to files and directories in a multiuser environment. It explains how to view and modify permissions using the 'ls' and 'chmod' commands, detailing both symbolic and absolute modes for setting permissions. Additionally, the chapter covers the umask value, which influences the default permissions assigned to newly created files and directories.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Linux Unit 4 For Later
Chapter 6
Securing Files in Linux
Vdd U Tee
ntroduction
t
J >ile Access Permissions (FAPs)
pe. a multiuser environment, such as Linux, multiple users work on the system simultaneously.
ge —-Jhese users share system resources, such as the hard disk, memory, and devices attached to
- ¢ system. Therefore, one of the important tasks of an administrator is to manage the files
=e directories of the users and groups.
pe Pach user on the Linux system is assigned a user login name, a password, and a group or
BFP © which the user belongs, Consider that you along with your coworkers are working
na project, and all of you need to read, write, or execute a set of files. Other users on the
BB Peswork should not have access to this set. To do this, you can ereate a group and add the
ers working on the project to this group. Now, you can grant permissions to this group on
Aye set of files so that they can be accessed.
Ay
Linux, file access permissions (FAPs) help to secure files and folders. File access
By nermissions refer to the permissions associated with a file with respect to the following:
4
© The file owner
© The group owner
© Other users
UG
‘The permissions that can be granted or revoked are symbolically represented by the letters r,
a, and x and are grouped together as rwx for different users in Linux,
e
1 permissions for a file or a directory are:
st
-Indicates the read permission. It can be represented by the number 4,
Indicates the write permission. It can be represented by the number 2,
) Indicates the execute permission. It can be represented by the number 1.
SUG
v
|Operating System: Linux
The following table summari;
Linux:
Table 6.1: File Access Permissions
izes the access permissions available for files and directories in
Action permitted on a file
‘Action permitted on a directory
Allows you to display, copy, and
compile the fil.
‘Allows you to list the contents of the
directory.
Allows you to edit, rename, and
‘move the file to another location,
Allows you to create new files and
subdirectories within this directory.
Access type] Denoted by
| Read e
| Write w
| Execute x
Allows you to execute the file with
the read permission.
‘Allows you to move to the specified
directory using the ed command,
Wes aee
i
Viewing File Access Permissions
As mentioned earlier, you use the 1s command to display the names of files. When you use the
~1 option with the 1s command, the command displays the names of files with the date and
time of creation, size, user name, group name, and access permissions for the file.
Let us understand how you can assign permissions in Linux by using the following sample
directory list:
Example
@
([Steve@localhost Steve] $ 1s -1
total 21 oy
-rw-rw-r 1 Steve Steve 134 Sep 21 10:48 DEADJOE
drwxr-xr-x 5 Steve Steve 1024 Sep 20 23:30 Desktop
drwx— 2 Steve IRDTECH 1024 Sep 22 09:00 Mail
-rwxr-xr-x 1 Steve IRDTECH —«-12901 Sep 22 03:44 [Link]
drwxrwxr-x 2 Steve —- Steve 1024 Sep 22 02:11 baseball =
drwxrwxr-x 2 Steve Steve 1024 Sep 21 10:42 basketball c
-rw-rw-r— 1 Steve Steve 58 Sep 22 03:44 [Link]
drwxrwxr-x 2 Steve Steve 1024 Sep 21 22:56 tennis a
FAP
7 Fs w z xv - - r - -
4 i i i
Type of File Owner permissions Group permissions Other users’ permissions
Figure 6.1: File Access Permissions
120qs.
ys
~
i Securing Files in Linux
“ “the first ch: indi
meen The senandicntea the type of file, such as an ordinary file, a hidden file, or a
. : of three characters display the read, a permissi
& next set yy the read, write, and execute permissions,
af that order, for the file owner. The followi the perm the
. ing three characters are the permissions for the
eon permissio
= P Owner, and the last three are the permissions for other users,
te the permission is available, w, oF x i
displayed; else a hyphen is displayed.
for the file [Link], the file owner is assigned the read, write, and
‘ecute: Permissions, while the group owner and other users are assigned the read and
‘aXecute permissions,
“in the example above,
ay
‘or directories, you need to interpret FAPs as follows:
\e read permission allows a user to:
te
© List the contents of a directory.
Fhe write permission allows a user to:
© Copy files to a directory.
© Remove files from a directory.
© Rename the files in a directory.
© Make a subdirectory.
© Remove a subdirectory from the directory.
© Move files to and from the directory.
dddddddd
e execute permission allows a user to:
7 © Change to a directory.
© Display a file in a directory.
© Copy a file from a directory.
i °changing File Access Permissions
bite
‘You can modify the access permissions associated with a file or a directory by using the chmod
1 command. However, only the owner of a file can change the permissions associated with it.
|
Permissions can be granted to the:
2 File owner, represented by the letter u
I 7) e Group owner, represented by the letter g
: 9 © Other users, represented by the letter o
|
: You can use the chmod command to grant or revoke permissions for files and directories.
imq
Operating System: Linux Ss Ee
The permissions for a file or directory indicate the actions that can be performed on the file
or the directory. L.
aes . EK
‘When using the chmod command, you use the + sign to grant permissions, and the ~ sign ¥
revoke permissions.
ne
The syntax for the chmod command is shown below: us"
symeax -s'
cf
chmod
‘You use the chmod command to specify the mode (permission to a type of user) in the
following ways: ce
© Symbolic — The permission and the user type are specified as symbols Cg
© Absolute — The permission is specified as a number € Ct
The following command shows the use of the chmod command: c Ez
Example ¢ Er
[steve@localhost Steve] $ chmod g+x [Link] ¢ € C
[steve@localhost Steve] $ chmod o-w [Link] é ¢ =
In the first example, the group owner is granted the permission to execute the file, [Link].
In the second example, the permission to write to the [Link] file is revoked from other =
cn
Symbolic Mode
In the symbolic mode, you use symbols to specify the permissions and the types of users, a
such as file owner or others, to whom the permissions are to be granted or revoked. a
users.
The following table explains the symbolic representation of entities:
cc
Table 6.2: File Access Permissions om
| symbol ~ Meaning 2
[ u Owner of the file or directory Cc
| 9 Members of the same group
| ° All other users 2
a All users
‘
122 4
’uv a ‘Securing Files in Linux
“ me To modify the permissions for a file, the file owner must specify:
vu © The type of user for whom the permission is to be modified
wo = © The type of permission that is to be modified
w me © Whether the permission is to be granted or revoked
Ps = ‘* The name of the file for which the permission is to be modified
i en allows you to change FAPs fora specific user type. Let us now look at some examples
t demonstrate the use of FAPS,
G ~ iis
G = [Steve@localhost Steve] $ 1s -1 x.c
Cc =~ “EW-rw-r~ 1 Steve TRDTECH 50 Sep 22 21:01 x.c
c = [Steve@localhost Steve] $ chmod utx x.c
c Bre ‘uw’ indicates the file owner, ‘+’ indicates that the permission is to be given, °x’
C
"i indicates the execute permission, and ‘x.c’ represents the file name.
fier the above command is executed, the FAP for the file x.c will be modified as follows:
[Steve@localhost steve] $1s -lx.c
-rwmrw-r- 1 Steve TRDTECH 50 Sep 22 21:01 x.c
‘To remove the read permission from the group owner, type the following command:
[steve@localhost Steve]$ chmod g-r x.c
» ‘g” indicates the group owner, and ‘-’ indicates that the permission is to be removed.
< permissions will now appear as follows:
< [Steve@localhost Steve]$ ls -1 x.c
~IWX-W-r— 1 Steve IRDTECH 50 Sep 22 21:01 x.c
'o remove the read permission assigned to other users, you need to type the following
mmand:
[Steve@localhost Steve] $ chmod o-r x.c
€
“f uF
é
lere, ‘o” indicates other users.
1e permissions will now appear as follows:
[Steve@localhost Stevel$ 1s -1 x.c
-rwx-w— 1 Steve IRDTECH
Linux also allows the file owner to change permissions for all the categories of users.
50 Sep 22 21:01 x.c
an 123
Oh aOperating System: Linux
To remove the execute permission for all the users, type the following command:
[Steve@localhost Steve] $ chmod a-x x.c
Here, ‘a’ indicates all the users.
The FAP for the file x.c will now appear as follows:
[steveelocalhost Steve]$ 1s -1 x.c
-rww— 1 Steve — IRDTECH 50 Sep 22 21:01 x.C
Note that all the instances of x have been replaced by hyphens. ss
‘To add the execute permission again, the file owner must type the following command: cpg
[Steve@localhost Steve] $ chmod a+x x.c fg
‘After specifying the above command, the FAPs for the file x.c appear as follows:
[steve@localhost Steve]$ 1s -1 x.¢ =
-rwx-wx-x 1 Steve — IRDTECH 50 Sep 22 21:01 x.c
Absolute Mode
In the absolute mode, you use a series of digits to represent file permissions. Using the
absolute mode is more convenient than using the symbolic mode because you can specify
different permissions for all the types of users in one statement.
Permission 2. Bes
4 Read
2 Write
1 Execute
The figure below depicts a sample representation of absolute numbers:
Ewe ew 7 OF
“ . ay
Sum is 7 Sum is 6 Sum is 4
Figure 6.2: Sample Representation of Absolute Numbers
The following table explains the number that denotes each type of permission:
Table 6.3: Absolute Numbers for Permissions
CY
Securing [Link] Linux
Ai
Yee
af onsider that you need to assign the read permission to users in the other category on all of
files with the extension .txt in your home directory.
‘ou can assign permissions by using the following command:
’}‘AD
[Steve@localhost Steve] $ chmod 664 ~/*.txt
, the first octet is for the file owner, the second octet is for the group owner, and the
third octet is for other users.
1¢ following table explains some of the permissions that are allocated when you specify a
icular absolute mode with the chmod command:
ae
Table 6.4: Modes and Output of the chmod Command
Mode Used with the | Permission of the File | Meaning S
chmod Command | after the Command
‘500 x ‘Assigns read and execute permissions to the file
owner.
61 “rW—x—x Assigns read and write permissions to the file owner
and the execute permission to group owner and other
users.
400 - ‘Assigns the read permission to the owner.
6 aw ‘Assigns read and write permissions to other users.
61 —rw—x ‘Assigns the execute permission to other users and
the read and write permissions to group members.
741 -rwxt——x. ‘Assigns read, write, and execute permissions to the
‘owner, only the read permission to group users, and
only the execute permission to other users.
7 “Pw xrWxrWX. Assigns read, write, and execute permissions to the
‘owner, group user, and other users.
a)
iple
"
[steveelocalhost Steve] $ chmod 722 empfeedbk. txt
y using the absolute mode with the chmod command, Steve has assigned the read, write,
id execute permissions to the file owner and the write permission to group users and other
ers for the [Link] file,
Ve
he umask Value
‘When you create a file, the umask value and the mode value determine the initial file
2
33)
125
*=
a
a
a
reayey
permissions. The mode value indicates that all the users have read and write peratable files. c
a file. By default, the mode value is 666 for files and 777 for directories and ex aa vetve.:, a e
To derive file access permissions, the value of umask is subtracted from the mo |
ich means
By default, the umask value is given as 002 for user and 022 for root user, ely @ .
that each file that a user creates has the permission, 666 - 002 = 664 (rw-r io
is
A
‘As you notice, the user and the group have the write permission. The primary group of the
user is, by default, the group owner of all the files that the user creates. 2
The umask value is specified in the /etc/profile file. You can use the umask command to
print or modify the umask value of files and directories. To ensure that the default file a c
permissions are same across the various sessions in Linux, the umask command is stored in
the .bash_profile file. When a new Bash shell is created, the umask command is executed a
automatically.
The syntax for the umask command is shown below: €
Syntax ia
umask [ value ] c
Here, value is an octal number of up to three digits. If you do not specify a value, the umask @
command retums the current umask value. If you specify an octal number less than three @.
digits, the operating system interprets the number as a number that contains leading zeros.
For example, if you specify a value of 77, the umask command is interpreted by the Cc
operating system as 077.
&
The following table depicts the effect on files that are created by using the various umask — ©
values. In the table, the umask values are listed in decreasing order of security: C
Table 6.5: Values and Output of the umask Command on Files Cc
Value Used with Permission of the Meaning ¢
the umask Command | File after thé Command
066 ‘Assigns read and write permissions to @ user and | ©
no access for group or other users. Cc
026 Assigns read and write permissions to a user; read |
Permissions to group, and no access to other users.
006 “ww Assigns read and write permissions to a user and
group but no access to other users.
022 “twtr
Assigns read and write permissions to a user; read
Permissions to group; and read permission to other
users.
126A
€
ee
=
Securing Files in Linux
“~S SYS & OC
€
symbolically represented by the letters x, w, and x where r indicates the read permission
id can be represented by the number 4, w indicates the write permission and can be
resented by the number 2, and x indicates the execute permission and can be represented
the number 1.
> ly
ile access permissions refer to the permissions associated with a file with respect to the file
mer, the group owner, and other users. The permissions that can be granted or revoked
‘\
1u use the Is -1 command to view file access permissions (FAPs).You use the chmod
ind to modify FAPs. You can use the chmod command in the symbolic and absolute
modes, and the umask command to modify the umask value of files and directories.x Chapter 7
Automating Tasks Using
Shell Scripts
SF troduction
a Shell as a Command Interpreter
shell is an intermediary program, which interprets the commands that are typed at the
‘command prompt. The shell translates the commands that you type into commands that are
derstood by the kernel. The shell acts as an interface between the users and the kernel
.d eliminates the need for a programmer to communicate directly with the kernel.
aa unique feature of the Linux operating system is that all Linux commands exist as utilities.
‘These utilities are located in individual files in any of the system directories, such as /bin, /
., or /usr/bin. The shell enables a user to access all the other utilities and resources of the
"etc,
Ca omputer.
When you enter text, the shell reads the first word at the command line to identify if it is an
Jias, a function, or an internal command, If the first word at the command line is a
Y ommand, the shell searches the directories specified in the path for the command. When
we Dhe shell finds the file associated with the command, it executes the file.
“=o process of command interpretation by the shell is as follows:
“as © When you log on, the shell displays the Linux prompt, indicating that it is ready to
execute commands.
When you give a command, the shell perform the following tasks:
© Reads the command.
® Searches for and locates the file, which has the same name as the command, in
the directories containing utilities.
Loads the appropriate utility into memory.
® Executes the utility.Operating System: Linux
. sl 3
After completing execution, the shell displays the prompt again, indicating that you can ente!
the next command,
The following figure depicts the process of command interpretation:
The shell displays the
prompt on the screen
The shell waits for ‘You enter a
the command to command
complete “
execution
The shell interprets
and executes the
command
‘Figure 7.1: Command Interpretation by the Shell
If the shell cannot locate a file corresponding to the command that you enter, the shell
displays an error message and then displays the $ sign.
Example
[Steve@localhost Steve]$ 1st filel
bash: Is'
[Steve@localhost Steve] $
command not found
The echo Command
‘You use the echo command to display messages on the screen.
Example
$ echo “This is an example of the echo command”
This is an example of the echo command
$
i
aAAAANANALEE OS
The echo command displays text enclosed between “ “ on the screen. By default, the echo €
command displays the text and then places a newline character at the end of it. The newline_
character moves the cursor to the next line after the text is displayed. To keep the cursor of
the same line, you can use the -n option with the echo command.
130
~
xans
Automating Tasks Using Shell Scripts
Example
$ echo -n “This will keep the cursor on the same line”
Notice that the $ sign is displayed on the same line as the output.
pes
Executing a Shell Script
Shell scripts can be used to automate tasks. Consider a situation in which you have a
sequence of Linux commands that you use frequently. Linux enables you to group the
. commands and execute them at once. You can store the commands in a file. The shell can
read the file in which the commands are stored and execute them. Such a file is called a
script file. You can also manipulate variables in shell scripts. In addition, shell scripts allow
you to use iteration constructs for programming. a
To create a script file, you need to write commands in a text file by using a text editor, such
as the vi editor, After you create the script file, you need to execute it, Let us say that you
create the following file named magic that you need to execute:
#1/bin/bash
echo “This is my first bash script”
In the magic file, the first line of the file informs the shell to execute the script file by using
the bash shell. You can also use other shells, such as sh, tcsh, or ksh, to execute shells
scripts. When you create a script file, the # and! characters should be the first two
characters of the script file followed by the interpreter that should be used to execute the
file. For example, if you need /bin/ksh as the interpreter for the script file, you need to
include #! /bin/ksh at the beginning of the shell file.
You can execute the magic file in either of the following ways:
1. At the command prompt, type:
$ bash magic
If there is an error in the first line of the shell script that you are executing, you might receive
the “No such file or directory” error message. To resolve the problem, type the whereis
bash command to locate the path of the bash program, and use the path in the shell script.
2. At the command prompt, type:
$ chmod u+x magic Change FAP
$ ./magic Execute the shell script
131To execute a shell script directly at the $ prompt,
file. When you acquire the execute permission, you can execu
Operating System: Linux 7
you need to change the FAPs for the script
te the shell script by typing its
name at the $ prompt.
When you log on to Linux, you begin work in a copy of the shell, known as the login shell.
As discussed earlier, the shell is a utility. Therefore, you can create a shell by executing the
shell command. For example, you need to execute the bash command to create the bash
shell. The new shell is known as the subshell or child shell of the current shell.
When you execute a shell script directly at the $ prompt, the current shell creates a child
shell to execute a shell script. The creation of the child shell ensures that the script does not
affect the current shell. The shell script is passed to the child shell for execution. The child
shell is terminated as soon as the shell script completes execution.
Example
The following file is named hello:
#!/bin/ksh.
echo “Hello”
echo “World”
Change FAPs for the script file using the following command:
$ chmod u+x hello
$ ./hello
Hello
World.
In the above example, the first line specifies that the shell script should be interpreted by
using the Korn shell (ksh).
Inserting Comments
You can include comment entries in a shell script by prefixing statements with the # symbol.
When the shell encounters the # symbol, it ignores text following the # symbol ina line.
Example
#!/bin/bash
echo “Hello”
#This is a comment line. This would not display any output.
echo "World"
ee mM MANA TTAKR OHA OAHAAYDAutomating Tasks Using Shell Scripts
yutput will be displayed. In a shell script, you can add comments about the structure and.
‘working of the shell script for future reference.
Variables
u™
um
un ‘In this example, the third line is a comment. The comment will be ignored by shell and no
J
-
f
rn
rn
Creating Variables
In the bash shell, you do not need to declare variables explicitly. Variables can be created at
hny point of time by simply assigning a value. A variable can be created without a value by
leaving the right-hand side of the assignment operator(=) blank. The syntax for creating a
variable is given below:
syntax
=
When you declare a variable, ensure that there is no space on either side of the
Not
assignment operator.
‘ou need to enclose the value within either single or double quotes.
xample
name="John Lennon”
lowever, you need not use the quotation marks if the value does not have any embedded
paces.
[n shell scripts, you cannot declare variables as integers or characters. All the variables in
e Linux operating system are treated as character strings. However you can perform
?,rithmetic operations on variables.
ample
name=Paul
ctr=1
in the above example, ctr does not contain a numeric variable. The ctr variable contains a
haracter string. Therefore, the ctr variable contains the character “1” and not the number 1.
“ 133ae =
Operating System: Linux i “-
: le iable
You can create variables either in shell scripts or at the shell prompt. If you create a variab c
tes execution. In |
within a shell script, the variable ceases to exist when the script complet
contrast, if you create a variable at the shell prompt, the variable exists until you log off. Ce E
When you log off from a Linux session, the Linux operating system closes all the applications =
that are running, including the login shell.
q
Referencing Variables
The $ symbol is used to refer to the contents of a variable. For example, to assign the value T
of one variable to another, you can use following the command: 1
Cc
variablel=${variable2} Cc,
In the above example, the value of variable? is assigned to variablel. c
‘The braces are used to delimit the variable name. For example, consider a variable named ¢ I
today that contains the value 20 and another variable named x. You need to assign the a J
value 20th to variable x by concatenating the value of the variable today with the string
th. To concatenate the values, you will use the following command: c
§ x=${today} th Cc .
Now, x would contain the value 20th. Cc
However, the following command will not produce the desired result because the shell woul _
look for a variable named todayth: —
$ x=$todayth Cc
The braces are optional in case you are not concatenating variables. Therefore, the following .
two commands will have the same result:
$ x=Stoday CS
eo
$ x=$ {today}
C
C
Reading a Value into a Variable
Besides allowing you to assign a value to a variable, the shell also lets you specify a value fo
a variable by using the keyboard. You can enter the value into a variable during the executiC~
ofa shell script by using the read command.
$ read fname
The read command can be used at the shell prompt but is usually used in shell scripts.
'innna
134v Automating Tasks Using Shell Scripts
\ On execution, the read command waits for you to enter a value for the variable. When you
press the key after entering a value, the remaining part of the shell script, if any, is
executed. The read command does not prompt you to enter data. However, you can use the
echo command to display a prompt.
$ echo “Enter your name”
Enter your name
$ read myname
Angela
In the above example, when the echo command is executed, a message is displayed.
However, after the read myname command is executed, the operating system waits for
input. Let us say you enter Angela and press the key. The value, Angela, is
$ echo $myname
Angela
_ © The following example explains how you can use echo and read commands to accept
U data from users in a shell script.
© Assume that you need to store the names and phone numbers of various callers at a call
center in a file called customerdata. The customerdata file should have the following
format:
Angela: 9123-21312
“I steve:934-2342
<3 Martin:932-2342
mp Yack:9182-1233
David: 932-12312
You need to write a shell script that accepts the required details and stores them in the file.
The flowchart given below represents the logic required to solve the given problem:rating System:
/‘ccept name /
Accept
number
Store data in a file
Figure 7.2: Flowchart Representing the Logic of the Shell Script
c
J
To store the names and phone numbers, you first need to accept customer details. Then, yo
can use the echo command to prompt the user to enter data. Next, you need to use the read
command to accept the values from the user. Finally, you need to store the details in a file by
using the >> operator.
Aaannn
0
v
na
You can use the following shell script, storedata, to accept details of customers:
#!/bin/bash
echo “Enter the name of the customer."
read name
echo “Enter the mobile phone number.”
read number
echo “$name: $number" >> customerdata
You can execute the storedata shell script by using the following command:
$ bash storedata
Alternatively, you can acquire execute permission for the shell script and execute it as
follows:
$chmod +x storedata
$ ./storedata
136
ANAKRNNAHNNANNNAvs
-
- v
Automating Tasks Using Shell Scripts
me S ‘When you execute the storedata shell script, the following screen is displayed:
O55 ./etoredata
Enter the name of the customer.
David
Enter the mobile phone number.
= 93-1231
‘The values that you enter are stored in the customerdata file. You can store multiple records
= by executing the storedata script repeatedly. To view the details of the customerdata file,
,
,
you can use the cat command.
Vv
— § cat custonerdata
Angela:9123-21312
Martin: 932-2342
Jack: 9182-1233
David: 932-12312
ve
Y
©
a’ Check Your Understanding
Write a shell script that accepts the name of the user. After accepting the name, the shell
~ script should display the following message:
D “Welcome to shell programming: ”
> in the message, denotes the name entered by the user.
7?
AB Local and Global Shell Variables
2
2 When a variable is referenced, only the shell that created it is aware of the variable. When a
new shell is created, it is unaware of the variables created in the parent shell. Now, the same
“=D variable name (as in the parent shell) can be given a different value without the parent shell
«xg knowing about it. Such a variable is called a local variable.
2 When you create a variable, it is accessible only in the shell in which you creaté it. The
2 subshells or the parent shell of the current shell cannot access the variables of the current
=" shell.
a
?
131
a02
Operating System: Linux
The following example explains the concept of a local variable:
$ continent=africa
$ echo “$continent”
Africa
$ sh Creates a child shell
$ echo “$continent”
There is no response
$ continent=Asia Gives a new value, Asia to continent
$ echo “$continent”
Asia
Press d
$ exit Displays exit and returns to the parent shell
$ echo “$continent”
Africa Parent is unaware of Asia
$ sh Creates another child shell
$ echo “$continent”
Continent does not have any value
Press d_
uv v . ,
$ exit Displays exit and returns to the parent shell
va o
$ echo “$continent”
= Africa Parent shell continues to have the value africa
“ $_
w
ow
c
c
c
Environment Variables
In a multiuser operating system, such as Linux, each user works on a copy of the shell. Each
shell has a set of special variables called environment variables, which users can edit to
configure the shell’s environment. By changing the values of environment variables, a user
‘can customize the environment.
‘Some examples of environment variables are HOME, PATH, PS1, PS2, LOGNAME, SHLVL,
and SHELL.
ame HOME Variable
In the Linux operating system, each user has an associated directory called the home
ay eiecon. When a user logs on, by default, the user is taken to the corresponding home
directory. The location of the home directory of a user is stored in the environment variable
HOME. For example, if the home directory for the user Roger is /home/Roger, then the
= variable HOME will contain this value.
3Operating System: Linux _
You can access the HOME variable the same way as you refer to other user-defined on
variables. For example, the following command will display the value of the HOME variable:
$ echo $HOME a
cy
The Patx Variable Cc 1
J
The PATH variable contains a list of colon-delimited path names of directories that are to be ¢_
searched for an executable program.
For example, the following command specifies that the directories to be searched for any
executable or command are /usr/bin and /bin, in that order:
$ PATH=/usr/bin:/bin.
When you specify the path, you do need to change to the directory containing the executable
file, You can execute the program, regardless of the current working directory.
By default, the Linux operating system does not search the current directory. Only the
directories specified in the PATH variable are searched. Therefore, if you need to search the
current directory, you need to specify the path of the current directory in the PATH variable. “
You can specify the current directory in PATH variable by using a period. c
Cc
Example c
a. PATH=/bin:/usr/bin:. - Searches in the order: /bin, /usr/bin, and
the current directory G
b. PATH=.:/bin:/usr/bin - Searches in the order: the current directory, C
/bin and /usr/bin
c. PATH=/bin: .:/usr/bin - Searches in the order: /bin, the current Cc
directory and /usr/bin c
While executing a file, the Linux operating system is searched in the order specified inthe ©
PATH variable.
Tip: Instead of executing a shell script, say magic, by typing the command $./magic at the
command prompt, you can execute a shell script by executing the command as $ magic if C
the current directory is specified in the PATH variable.
: &
The psi Variable ¢
The PS1 or Prompt String 1 variable contains the shell prompt, the $ symbol. You can re
change the shell prompt by editing the value of the PS1 variable.
c
40 a
c
ar,Automating Tasks Using Shell Scripts
1¢ following command will change the shell prompt to HELLO>:
PS1="HELLO>”
HELLO> ‘New prompt
‘While changing the shell prompt, ensure that there are no spaces before and after the = symbol.
’AIso, enclose the new prompt within quotation marks.
‘ou can also use certain predefined prompt strings to specify the value of the PS1 variable.
‘or example, you can use the, \w string to display the current working directory.
Pee
xample
$ PS1="\w >’
~ >ed /usr/doc
Jusx/doc >_
the above example, after you change the value of the PS1 variable, the prompt displays
¢ tilde (~) symbol, denoting your HOME directory. In addition, the prompt changes when
mu change to another directory.
‘ou can use the man bash command to refer to the man pages for the bash shell and view
the prompt strings of the PS1 variable.
om
e ps2 Variable
‘he PS2 variable specifies that the value for the secondary prompt. By default, the
.econdary prompt is the > symbol. The Linux operating system displays the secondary
rompt when you type an incomplete command on the command line.
ya
Example
§ PS1="$
>
>+
a
In the above example, the value of the PS1 variable is enclosed within quotation marks but
1e quotation marks are not closed. As a result, the command is considered incomplete.
lotice that the > prompt is displayed because of the incomplete command.
PCT
4
You can use the following command to change the PS2 prompt:
tt
$ PS2=*
$ echo “This is incomplete
“close the quotes
AGUOperating System: Linux
The LOGNAME Variable
‘The user’s login name is stored in the LOGNAM# variable.
Example
$ echo “${LOGNAME) ”
‘You might or might not enclose the LOGNAME, variable in quotation marks and braces.
Alternatively, you can give the following command:
$ echo $LOGNAME
The sHLvu Variable
The SHLVL variable contains the shell level that you are currently working in. When
working on Linux, you might create new shells and forget the level of the shell in which you
are working. In such a situation, you can use the SHLVL environment variable to know the
level of the shell in which you are working. In the Linux operating system, the login shell is
assigned the number 1. When you create a new shell, the value of the variable SHLVL is
incremented by one.
Example
S$ echo $SHLVL
1 This is the login shell.
$sh Creates a new shell.
$ echo $SHLVL
2° You are working in the new shell.
$ exit Terminates the child shell.
exit
$ echo $SHLVL
Returns to the parent shell, which is the login shell in this case.
The sHELL Variable
The SHELL environment variable stores the default shell of the user. You can view the
value of the variable by using the following command:
$ echo $SHELL
/bin/bash
142
nlp gQgnnnnannnnnnm| \y
”
v
RH Automating Tasks Using Shell Scripts
‘You use the env command to view a list of all the exported environment variables and their
a
i?
The env Command
= PWD=/root
~REMOTEHOST=172..17 68.97
AHOSTNAME=server2 .[Link]
PVM_RSH-/usr/bin/rsh
QTDIR=/usr/lib/qt-2.3.0
LESSOPEN=| /usr/bin/[Link] %s
XPVM_ROOT=/usr/share/pym3 /xpvm
KDEDIR=;
AUSER=root
-MACHTYPE=i386-redhat-Linux-gnu
MAIL=/var/spool/mail/root
INPUTRC=/etc/inputre
BASH_ENV=/root/.bashro
AANG=en_US
AVOGNAME=root
~SHLVL=L
SHELL=/bin/bash
_USERNAME=root
HOSTTYPE=i386
Tespective values.
‘The following example is an output of the env command:
mm <3 ene
/ S osryPE=linux-gau
i.
|
2
?
aD
9 usr/local/sbin: /usr/local/bii
D HISTSIZE=1000
LAMHELPFILE=/etc/lam/lam-helpfile
PVM_ROOT=/usr/share/pvm3
D reRvextern
sss PHOME=/root
SSH_ASKPASS=/usr/1ibexec/openssh/gnome- ssh-askpass
PATH-/usr/local/sbin: /usr/sbin: /sbin: /usr/kerberos/sbin: /usr/kerberos/bin: /
/sbin: /bin: /usr/sbin: /usr/bin; /usr/X11R6/bin: /
root/bin
=/usr/bin/envNy)
Operating System: Linux oT
Command Substitution
" ‘ . ymmand
In addition to pipes, you can use command substitution to combine more than one CO"
ina command line.
Suppose that you need to display the following message on the screen:
The date is (output of the date command)
To do so, you can enter any the following command:
echo “The date is ‘date’”
The command date is enclosed in single backward quotation marks or a grave accent.
While executing the command, the shell first replaces the enclosed command with the output
of the command. Then, the shell executes the entire command.
an
pees
The following command would also display the same output:
echo “The date is $(date)”
The shell replaces $ (date) with the output of the date command.
The expr Command
In most shells, you cannot declare variables as integers. All variables are treated as
character strings. Therefore, in'the following declaration, the variable var 1 contains the
characters 2 and 5, and not the number 25:
varl=25
nee nnegnnrgns
However, in Linux, you can perform arithmetic operations by using the expr command to
simulate numeric variables and evaluate arithmetic expressions. The output of the expr
command is sent to the standard output file.
nN
Example
$ expr 4+ 5 Cc
The command in the above example will display 9 on the screen. Notice that you need to add @—
a space on either side of the + operator. C
You can use variables in the expr command. Consider the example given below. Cc
$ a= “
$ b=4 ©
$ expr $a + $b e
9
c
4 C
¢cwv
Automating Tasks Using Shell Scripts
The operators supported by expr command are +, ~, *, and /. However, when the * operator is
used, it should be preceded by the backslash character. If you do not precede the * operator
with the backslash character, the shell interprets the * operator as a wildcard character.
The expr command does not support decimals. The following command will display 2 and
not 2.5 because the numeric value after the decimal point is ignored:
OO
$ expr 5 / 2
Similarly, the following command will result in a syntax error because the decimal point in 2.5
will be treated as a period:
ons
$ varl=2.5
$ expr $varl + 5
‘Therefore, the expr command will treat the value of the variable var1 as numeric.
As stated earlier, the output of the expr command is displayed on the standard output file.
However, if you require that the output of the expr command should be stored in a variable,
you can use command substitution. For example, the following command-will assign the
value 25 to the var variable:
c
ro
Vdd Jee
expr $varl + 20°
use of the expr command is shown in the following code:
ge
sa)
a=10
b=5
a=/expr $a - 7!
echo “a is equal to $a"
a=‘expr $a \* $b!
echo “a is equal to $a"
as/expr $a / 3’
echo “a is equal to $a”
‘The output of the code given above will be as follows:
ess)
a
¢
"e
YVuseYNU
a a
i a is equal to 3
J a is equal to 15
i ow * is equal to 5
-2arithmetic Expansion
»
"To calculate the value of an expression, you can enclose the expression in $ ((.. ))-
u
SDOperating System: Linux
Syntax
$ ((expre:
Example
on))
$ echo $((45+34))
79
To calculate the sum of the numbers, 45 and 34, you can enclose the numbers in ((_)) along E
with the + operator. In addition, you can use the — operator for subtraction, the * operator for
multiplication, and the / operator for the division of two numbers. While enclosing the cy
expression in ((..)), you can also specify variables instead of numbers in the expression. Coy
Example co
$ a=25 S
S$ b=56
ss
$ echo $((a+b))
81 —_
Consider a scenario in which you need to create a shell script that calculates the number of C=
unanswered queries at the call center of ABC Telecommunications. The shell script should a
accept the total number of queries reported in a day and record the number of queries ;
answered to calculate the number of unanswered queries. Cc
The flowchart given below represents the logic required to solve the given problem:
‘Accept total number
of queries
Accept total number
of queries answered
Vv
Calculate pending queries
v
Display pending queries |
Figure 7.3: Flowchart Representing the Logic of the Shell Script
G
&
©
C
¢
¢
C
4
(- ty °
= Automating Tasks Using Shell Scripts
49 You can use the callpending shell script to calculate the number of unanswered queries.
echo “Please enter the total number of queries reported today.”
y ead totalqueries
echo “Please enter the number of queries answered.”
v read answered
mo ((totalqueries-answered) )
(echo “Number of calls pending = Spending”
a Y You can execute the shell script by using the following command:
6 bash callpending
U Alternatively, you can acquire execute permission for the shell script and execute it in the
SS) following manner:
$ chmod +x callpending
= $ ./callpending
When you execute the callpending shell script, the following screen is displayed:
= $ bash callpending
ec¢ce
Yorease enter the total number of queries reported today.
U2120
RyPlease enter the number of queries answered.
109
MH susver of calls pending = 11
=~
a
it 2Summary
Ces
ry The echo command is used to display messages on the screen. Shell scripts allow you tc
i ‘manipulate variables and use iteration constructs for programming. Comment entries can |
Dincluded in a shell script by prefixing statements with the # symbol. When a variable is
referenced, only the shell that created it is aware of the variable._
fables to the child shell.
ps2, LOGNAME,
‘on, while the €xPr
Operating Syster
The export command can be used to pass the parent shell vari
‘Some of the environment variables are HOME, PATH, PS1,
SHLVL, and SHELL. The grave accent is used in command substituti
command is used to evaluate arithmetic expressions.
You can enclose an expression in $ ( (...) ) and calculate its value. You can calculate
arithmetic expressions by using command substitution.
“
G
Cc
C
¢
¢