mca3030 unit 02 slm
Post on 02-Oct-2015
230 Views
Preview:
DESCRIPTION
TRANSCRIPT
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 21
Unit 2 Shells and Utilities
Structure:
2.1 Introduction
Objectives
2.2 Getting Started with Shell Programming
Bash shell
Shell commands
The role of shells in the Linux environment
Other standard shells
Writing a simple shell script
Comments in a script
Setting up permissions on a script
Executing a script
Debugging a script
2.3 The Shell Variables and Environment
Variables in shell
Bash variable existence check
Customize the Bash shell environments
2.4 Commonly Used Commands and Utilities
2.5 Summary
2.6 Glossary
2.7 Terminal Questions
2.8 Answers
2.1 Introduction
In the previous unit, you were given an overview of Linux as an operating
system and as a product. We discussed the history of Linux and Free Open
Source Software (FOSS) and more common distributions. You were also
provided an introduction to basic operating system principles from a Linux
perspective. You learnt about processes, files, and directories and the
basics of how a user interacts with the Linux system.
A command interpreter program that provides interface between some users
and the operating system itself is called the shell. The shell is a
programming language and it has some major benefits over other
programming languages. It interfaces easily and seamlessly with several
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 22
Linux utilities. Shell also expands wildcards into a list of filenames. Lists
present in a variable are automatically divided into their constituent parts.
Utilities help you to manage some very complicated processing and you can
consider utilities as commands or as prewritten programs. People using
Linux frequently send the output of one command or utility to another
command or utility for additional processing.
In this unit, we will discuss about the traditional way users interact with the
system, the shell. We will also explain the more common utilities and how
they interact with the shell. We will give an overview about user interaction
with the system, primarily from the command line.
Objectives:
After studying this unit, you should be able to:
explain the features of a Bash shell
provide an overview of the role of shells in the Linux environment
explain how to set up, execute, and debug a script
explain different shell variables and their environment
describe some commonly used commands and utilities
2.2 Getting Started with Shell Programming
Even if you are not a programmer, Linux is created with some features that
simplify your life. When there is a recurring task that involves entering Linux
commands or modifying the contents of a file, you must think about
automating the task with a program. With the help of Linuxs built-in
programming features, it is possible to automate recurring tasks and create
simple interactive applications. The default shell for most Linux systems is
the Bash shell.
2.2.1 Bash shell
The shell is considered as a program that serves as an interface or a
command line interpreter between the user and the operating system. The
shell has three major uses and they are:
Providing interactive use
Customizing Linux session by describing variables and startup files
Programming by writing and implementing shell scripts
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 23
The Free Software Foundation developed a replica of the Bourne shell,
written from scratch, termed as Bash (the Bourne-Again Shell). Eventually,
Bash has become a POSIX (Portable Operating System Interface for Unix)
compliant version of the shell and includes several popular features from
other shells, like csh (C shell), tcsh (TC shell), and ksh (Korn shell). The
GNU project developed the Bash shell for Linux which provides features
such as:
Wildcard characters (metacharacters) used for filename abbreviation
Input/output redirection
Shell functions for modularization of tasks within a shell program
Shell variables and options for modifying your environment
A built-in command created for writing shell programs
Command-line editing via the command syntax of either vi or emacs
Access to prior commands (command history)
Job control
Integer arithmetic
Command-name abbreviation (aliasing)
Arrays and arithmetic expressions
Internationalization facilities
Upward compliance with POSIX
An arithmetic for loop
More ways to replace variables
Bash is compatible mainly with Bourne shell. However, Bash runs on every
version of Unix and some operating systems including OS/2, MS-DOS, and
Window platforms.
2.2.2 Shell commands
There are two types of commands present in the Bash shell and they are:
Internal commands (built-ins) These commands form the part of the
shell itself as they are built into the shell.
External commands These commands separate binaries stored in
/sbin, /usr/sbin, /usr/bin, /bin, or /usr/local/bin directories.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 24
Table 2.1 depicts some common shell commands and their purposes.
Table 2.1: Shell Commands and their Purposes
Command Purpose
env This command lists your current environment variables
and their settings.
export If you are asked to set an environment variable, create the
variable and then use the export command to remember
the variable properly.
alias This command creates or lists command shortcuts
unalias This command removes command shortcuts
history This command lists the previous 1000 commands you
have typed
The Bash shell recognizes the following:
Keywords like if
Aliases like 11
Built in commands like pwd (print working directory)
Functions including user defined functions like genpasswd (generate
password)
Files such as /bin/date
The type command might be used to find out a command type.
The command interpreter for the Bash shell is invoked using:
bash [options] [arguments]
Bash can run the commands from:
A terminal
A file (when the first argument is an executable script)
Standard input (when no arguments remain)
If standard input is a terminal, Bash automatically prints prompts.
2.2.3 The role of shells in the Linux environment
Under Linux, the shell is used for different purposes.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 25
The Linux user environment is composed of some components and these
include:
Kernel This is the core of Linux operating system.
Shell This serves as an interface between the kernel and the user.
Terminal emulator In X Window System, the xterm program serves
as a terminal emulator. It helps the user to enter commands and display
their results back on screen.
Linux desktop and windows manager The Linux desktop is a
collection of different software applications. It includes the windows
manager, the file manager, the Terminal emulator, etc. The two
examples of the complete desktop environment in Linux include
GNOME (GNU Network Object Model Environment) and KDE
(K Desktop Environment).
Login shell
When a user logs into the system, the first shell started is referred to as a
login shell. Login shells create the environment which is exported to non-
login shells.
When a user logs in, login shell calls the following:
/etc/profile executes first when a user logs in runlevel #3 (the level
numbers may vary depending upon the distribution. You will be reading
about the runlevel in detail in Unit 3).
/etc/profile.d
$HOME/.bash_profile, $HOME/.bash_login, and $HOME/.profile,
executes second when a user logs in that order. $HOME/.bash_profile
calls $HOME/.bashrc, which calls /etc/bashrc (/etc/bash.bashrc).
Non-Login shell
When an interactive shell which is not a login shell is started, Bash reads
and runs commands from /etc/bash.bashrc or /etc/bashrc and
$HOME/.bashrc, if these files are present. First, it calls $HOME/.bashrc.
This calls /etc/bash.bashrc, which calls /etc/profile.d.
Bash startup scripts
These are the script of commands executed at login to create an
environment. For example, setup JAVA_HOME path.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 26
Bash logout scripts
When there is an exit of login shell, bash reads and runs the commands
from the file $HOME/.bash_logout, if it is present.
2.2.4 Other standard shells
A lot of work is performed in Linux using a command line shell. Bash is
preinstalled in Linux and also several other shells are available under Linux
which include:
csh This is a shell with C-like syntax, a standard login shell on BSD
(Berkeley Software Distribution) systems.
ksh This is an ideal, AT&T version of the Korn shell.
scsh This is an open-source Unix shell that is embedded within the
Scheme programming language.
tcsh This is an improved version of csh, the C shell.
zsh This is a powerful interactive shell.
Self Assessment Questions
1. The shell is considered as a program that serves as a __________
between the user and the operating system.
2. Name two types of commands present in bash shell.
3. Kernel is a collection of different software applications. (True/False)
4. Which among the following is a powerful interactive shell that is
available under Linux? (Pick the right option)
a) ksh
b) scsh
c) zsh
d) csh
2.2.5 Writing a simple shell script
The steps that are followed to create a shell script are:
1. Use a text editor like vi. Put necessary Linux commands and logic in
the file.
2. Save and close the file and exit from vi.
3. Execute the script.
4. Test the script. Once you obtain the desired output, move it to the
production environment.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 27
To create a file hello.sh using vi, give the following command.
Prompt$vi hello.sh
Enter the following commands to create a shell script to display Hello
World!.
#! /bin/bash
echo Hello, World!
Ensure that execute permission is allowed by giving the following
command:
Prompt$chmod +x hello.sh
Save and close the file. You can execute the script as follows:
Prompt$. /hello.sh
You will obtain the following output:
Prompt$Hello, World!
2.2.6 Comments in a script
You can add comments in a script to give others more information about
what the script does. Consider the following shell script:
#! /bin/bash
# A Simple Shell Script To Get Linux Network Information
The first line is known as a shebang or a bang line. If a line or a word starts
with #, then that word and the remaining characters on that line are ignored.
These lines are not the statements for Bash to execute and it completely
ignores them. These lines are known as comments and they are
explanatory text about the script. These lines make source code easy to
understand and they are for humans and other system administrators. They
help others to understand your code and logic and also allow them to modify
the script you have written.
We can comment multiple lines by adding
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 28
Consider the following shell script:
#!/bin/bash
echo a
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 29
To remove read and execute permission for the user and the group, you
must enter:
Prompt$chmod ug = script.sh
2.2.8 Executing a script
The execution of a shell script is done using the following syntax:
Prompt$chmod +x script.sh
Prompt$. /script.sh
You may also directly execute the script without setting the script execute
permission as follows:
Prompt$bash script.sh
Prompt$. script.sh
The . (dot) command (also called source) is used which reads and
executes commands from filename in the current shell. If filename does not
have a slash, directory names in PATH are used to find the directory
containing filename. When either the bash command or the dot (.) command
is used to run a script, it is not required to set executable permissions on
script.
2.2.9 Debugging a script
To debug a script, you must run a shell script with x option from the
command line itself by specifying:
Prompt$bash x script-name
or
Prompt$bash xv script-name
Use of set builtin command
The Bash shell provides debugging options which may be turned on or off
with set command in the following ways:
set x This will display commands and their arguments as they are
implemented.
set v This will display shell input lines as they are read.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 30
set n This will read commands but will not execute them. Verification
of a shell script for syntax errors is done using set n.
Self Assessment Questions
5. #! /bin/bash is known as the ________________ line in a shell script.
6. What is the syntax used to set the permissions for the user and the
group to read and execute the script script.sh?
7. When either the bash command or the dot (.) command is used to run a
script, it is not required to set executable permissions on script.
(True/False)
2.3 The Shell Variables and Environment
When you login, Linux will create certain parameters for your login shell.
These parameters can be in the form of features or variables. Linux
provides a predefined set of variables for both system and shell use and
these variables are allocated system values which in effect sets the
parameters. Linux sets up parameter shell variables which are used to
configure the user shell. When you login, the system defines most of the
parameter shell variables. The shell automatically creates some of the
parameter shell variables. The initialization scripts which are described later
set the other parameter shell variables. The shell directly sets certain shell
variables. Most of these variables are application specific and they are used
for tasks like history, mail, or editing. It is better to assume these variables
as system-level variables because these variables are used to configure the
entire system and create values such as the location of executable
commands on your system or the number of history commands permissible.
A reserved group of keywords is applied for the names of the system
variables. These keywords must not be used as the names of any of your
own variables. Uppercase letters are used to specify all system shell
variables, making it easy to recognize the variables. Lowercase letters are
used to specify shell feature variables. For example, the system uses the
keyword HOME to define the HOME variable which is a special
environment variable that contains the pathname of the users home
directory. Similarly, to set the noclobber feature on or off, the keyword
noclobber is used. Some commonly used system variables that are set by
the shell are depicted in table 2.2 along with their meaning.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 31
Table 2.2: System Variables with their Meaning
System variable Meaning
BASH_VERSION It holds the version of the instance of bash.
HOSTNAME It indicates the name of the users computer.
HISTFILE It indicates the name of the file where in command
history is saved.
HISTSIZE This variable specifies the number of commands to
remember in the command history and the default
value is 500.
HISTFILESIZE It indicates the maximum number of lines present in
the history file.
CDPATH It serves as the search path for the cd command.
IFS This is the Internal Field Separator used for splitting
word after expansion and for splitting lines into words
using the read builtin command and
is its default value.
HOME This is the home directory of the current user.
PATH This is the search path for commands and it serves
as a colon-separated list of directories wherein the
shell looks for commands.
PS1 This is the users prompt settings.
LANG This is used to verify the locale category for any
category not particularly selected with a variable
beginning with LC_.
TIMEOUT This is the default timeout for the read builtin command.
SHELL This is used to set path to login shell.
TERM This is the users login terminal type.
EDITOR This is used to set name of default text editor.
DISPLAY This is used to set X display name.
Note: You can add export command to the initialization file placed in the
home directory of your account indicated as follows: ~/.bash_profile.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 32
2.3.1 Variables in shell
Variables are used to store data and configuration options. There are two
types of variables and they are:
System variables The Linux Bash shell itself creates and maintains
system variables. Capital letters are used to define system variables
excluding auto_resume and histchars. The aspects of the shell are
configured by altering system variables including PS1, LANG,
HISTSIZE, DISPLAY, PATH, etc.
User-defined variables The user creates and maintains these
variables. These variables defined may use any valid variable name;
however, it is a good practice to avoid all uppercase names as many are
used by the shell.
Assign values to shell variables
It is simple to create and set variables within a script. To do this, you may
use the following syntax:
Prompt$varName = someValue
someValue is assigned to the specified varName and someValue must be
on right side of = (equal) sign. The variable is allotted the null string if
someValue is not given.
Default shell variable value
The default shell variable value is set with the following syntax. For
example, try to display the value of an undefined variable called
wimbledon.
Prompt$echo $wimbledon
Since the variable wimbledon was not assigned any value, nothing is
displayed. You can set the default value to Serena Williams and display it
by entering the following command:
Prompt$echo $ {wimbledon=Serena Williams}
You will obtain the following output:
Prompt$Serena Williams
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 33
Note: If there is an empty variable, a default value can be assigned and the
syntax is:
$ {var:=defaultValue}
Rules for naming variables
Following are the rules for naming variables:
Variable names should start with alphanumeric character or underscore
character (_). This can be followed by one or more alphanumeric or
underscore characters. Examples for valid shell variables are:
SYSTEM_VERSION
HOME
vech
no
When allotting value to variable, do not put spaces on either side of the
equal sign. For example, valid variable declaration is as follows:
no=10
However, any of the following variable declaration will cause an error
like command not found.
no = 10
no = 10
no = 10
Just like filenames, variable names are also case-sensitive.
no=10
No=20
NO=30
nO=4
In this case, all are different variable names.
echo $no # print 10 but not 30
echo $No # print 20 but not 30
echo $nO # print 4 but not 30
echo $NO # print 30
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 34
You can define a NULL variable as a variable that has no value at the
time of definition.
vech=
vech=
You must not use ?, *, and other special characters to name your
variable.
?no=10 #invalid
Display the value of shell variables
You can use either echo or printf command to display the variable value.
echo $varName
or
printf %s\n $varName
Quoting
Bash shell recognizes special characters with special meanings. For
example, variable value is expanded using $var. Bash expands wildcards
and variables, for example:
echo $PATH
echo $PS1
echo /etc/*.conf
However, sometimes you may not like to use variables or wildcards, for
example, do not print value of $PATH, but print $PATH on screen as a
word. The meaning of a special character may be enabled or disabled by
placing them in single quotes. This may also help to suppress error
messages or warnings when writing the shell scripts.
echo Path is $PATH ## $PATH will be expanded
echo I want to print $PATH ## PATH will not be expanded
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 35
There are three types of quotes and they are illustrated in table 2.3.
Table 2.3: Three Types of Quotes
Name and quote type Meaning Example (type at
shell prompt)
The double quote Double quote (quote)
protects everything
included between two
double quote marks
excluding $, , , and \.
Double quotes are
used when you like to
have only variables and
command substitution.
* Variable Yes
* Wildcards No
* Command
substitution yes
Double quote aids in
printing the value of
$SHELL variable,
disables the meaning
of wildcards, and
permits command
substitution.
echo "$SHELL"
echo "/etc/*.conf"
echo "Today is
$(date)"
The single quote Single quote quote
protects everything
included between two
single quotation marks
and it is used to turn off
the special meaning of
all characters.
* Variable - No
* Wildcards - No
* Command
substitution - No
Single quote avoids
displaying variable
$SHELL value,
disables the meaning
of wildcards/etc/*.
conf, and ultimately
command substitution
($date) itself.
echo '$SHELL'
echo '/etc/*.conf'
echo 'Today is
$(date)'
The Backslash - \ Backslash (\) is applied
to change the meaning
of the characters or to
escape special
characters within the
You may use \ before
dollar sign to indicate
the shell to have no
special meaning. The
meaning of the next
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 36
text like quotation
marks.
character in $PATH is
disabled (i.e. the
value of $PATH
variable is not
displayed).
echo "Path is
\$PATH"
echo "Path is $PATH"
The export statement
The export builtin automatically exports to the child processes environment.
For example, create the variable vech and assign it a value Bus.
Prompt$vech=Bus
To display the variable value with echo, you must enter:
Prompt$echo $vech
To begin a new shell instance, you must now enter:
Prompt$bash
To display back the value of a variable with echo, now enter:
Prompt$echo $vech
You will get an empty line because the variable vech is not exported to new
process. You must use the export command to make the child processes
identify the variable. Try to run the following example at a console or
terminal:
Prompt$export backup=/nas10/mysql
Prompt$echo Backup dir $backup
Prompt$bash
Prompt$echo Backup dir $backup
All user-defined variables are local by default and they are not exported to
new processes. Functions and variables are exported to child processes
with the help of export command. If there are no specified variable names or
function names or if there is p option given, a list of all names exported in
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 37
this shell is printed. An argument of n indicates to eliminate the export
property from subsequent NAMEs.
Prompt$export -p
Unset shell and environment variables
Unset command is used to delete the variables when executing the
program.
The unset command can remove both functions and shell variables.
Prompt$vech=Bus
Prompt$echo $vech # will display Bus
Prompt$unset vech
Prompt$echo $vech # will not display anything
Getting user input via a keyboard
The read command is used to accept input from the keyboard and allocate
an input value to a user-defined shell variable. This command has the
following syntax:
Prompt$read p Prompt variable1 variable2 variableN
where,
-p Prompt indicates display prompt to user without a newline.
Variable1 indicates the first input, i.e., word allocated to the variable1.
Variable2 indicates the second input, i.e., word allocated to the
variable2.
Self Assessment Questions
8. A reserved group of ___________ is applied for the names of the
system variables.
9. Which among the following is the system variable that indicates the
name of the users computer? (Pick the right option)
a) BASH_VERSION
b) HOSTNAME
c) CDPATH
d) HISTFILE
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 38
10. When allotting value to a variable, you must put spaces on either side
of the equal sign. (True/False)
11. _____________ is applied to change the meaning of the characters or
to escape special characters within the text like quotation marks.
12. _________________ is used to accept input from the keyboard and
allocate an input value to a user-defined shell variable.
2.3.2 Bash variable existence check
If there is no defined variable, you can stop executing the Bash script using
the following syntax:
$ {varName? Error varName is not defined}
$ {varName:? Error varName is not defined or is empty}
This is helpful for a sanity checking and if there is no variable defined, the
script will stop executing.
Example:
Create a shell script varcheck.sh.
#! /bin/bash
# varcheck.sh: Variable sanity check with :?
path=${1:?Error command line argument not passed}
echo Backup path is $path.
echo Im done if \$path is set.
Execute it as follows:
Prompt$chmod +x varcheck.sh
Prompt$./ varcheck.sh /hom
Outputs:
Backup path is /home.
Im done if $path is set.
2.3.3 Customize the Bash shell environments
The two types of shell variables are:
Local variables The shell or user scripts use these variables. It is
evident that all user-created variables are local variables unless they are
exported via the export command.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 39
Environment variables The shells or users use environment
variables, however, they are also passed onto other commands.
Environment variables are passed to subshells or sub processes.
The Bash shell is configured using the following:
Variables
shopt command
set command
To view all variables, the set built-in command is used:
Prompt$set
Usually, bash sets all upper-case variables, for example,
Prompt$echo $SHELL
Prompt$echo $MAIL
To export local variables, you can use the export command:
export EDITOR=/usr/bin/vim
# export DISPLAY environment variable and run xeyes
export DISPLAY=localhost:11.0 xeyes
Remember to be careful when changing the shell variables. A complete list
of variables created by the shell can be obtained by reading the man page
of bash. To read the man page of bash, type the following command:
Prompt$man bash
To view all environment variables, use the env command:
Prompt$env
Some common environment variables are:
PATH This variable is used for setting the users executable search
path.
HOME This variable indicates the users home directory path.
pwd This variable indicates the users current working directory.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 40
Recalling command history
Bash maintains a command history in buffer or a default file
~/.bash_history and the history buffer can include several commands. To
display a list of command entered at a shell prompt, history command is
used. The commands stored in history can also be repeated. The history
command also reveals the list of history with line numbers. By default history
is enabled; however, it may be disabled with set builtin command. The
basic command is recalled using the arrow keys.
To repeat the last command, type !! at a shell prompt:
Prompt$date
Prompt$!!
To recall the most recent command beginning with vn:
Prompt$date
Prompt$vnstat
Prompt$ls
Prompt$ifconfig
Prompt$route n
Prompt$!vn
To repeat a command by its number and recall to command line number 10:
Prompt$history
Prompt$!10
Path name expansion
The Bash shell supports path name expansion using the Curly brace
technique. A curly brace ({..}) expands to form a pattern and the syntax is:
{ pattern1, pattern2, patternN }
text { pattern1, pattern2, patternN }
text1 { pattern1, pattern2, patternN } text2
command something/{ pattern1, pattern2, patternN }
This technique saves command typing time and also helps in creating
arbitrary strings.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 41
The filenames created need not exist. You may execute a command for all
the patterns inside the braces. You can type the following syntax to list three
files:
Prompt$ls -1 /etc/resolv.conf /etc/hosts /etc/passwd
But with curly braces, the same command can be given as:
Prompt$ls /etc/ {resolv.conf, hosts, passwd}
To remove files like hello.sh, hello.pl, hello.c, and hello.py, enter:
Prompt$rm v hello. {sh, pl, c, py}
Create and use aliases
A shortcut to commands is called as alias. The alias command is used to
display the list of all defined aliases. User-defined aliases are added to
~/.bashrc file.
To create and use aliases, you can use the following syntax:
Prompt$alias name=command
Prompt$alias name=command arg1 arg2
Examples:
To create an alias c to clear the terminal screen, you must enter:
Prompt$alias c=clear
To clear the terminal, enter:
Prompt$c
To display the system date and time, create an alias d and enter:
Prompt$alias d=date
Prompt$d
Outputs:
Prompt$Mon Dec 19 02:45:56 IST 2010
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 42
Alias is developed and listed using the alias command, and removed using
the unalias command and the syntax is:
Prompt$unalias alias-name
Prompt$unalias c
Prompt$unalias c d
To list the currently defined aliases, you can enter:
Prompt$alias
Prompt$alias c=clear
Prompt$alias d=date
To unalias a command d, enter:
Prompt$unalias d
Tilde expansion
The variables provided by the Bash shell that are prefixed with ~ (termed
as tilde) are called Tilde Expansions. The Tilde expansions serve as
synonyms for contents of other variables with the users shell. The method
of changing abbreviations to the directory names that they stand for is Tilde
expansion. Tilde expansion is applicable to the ~ plus characters including
+, -, and N (integer) up to a slash.
The tilde expansion is also used to expand numerous specific pathnames
including:
Home directory
Current or previous working directory
Directories from directory stack
Let us now discuss these in brief.
Home directory
Tilde expansion helps to expand the home directory of the current user or
the home directory of the specified user name. Syntax is:
~ Expand to the variable $HOME or home directory of the current user
~USER Expand to the home directory of the given username
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 43
Working directory
Tilde with + or - can be applied for representing the working directories.
~+ is used as a shortcut to obtain the value of the PWD variable which
includes the current working directory.
~- is used as a shortcut to obtain the value of OLDPWD variable, which
includes the previous working directory.
Directories from directory stack
There is a stack object present in every bash process. The stack object is
used to record the directories visited by a script while it is processing data of
directory contents. It is a simple process used in reference directories or
used to change back to directories that were visited before. Tilde expansion
also expands the directories in the directory stack.
In the directory stack, ~+N expands the Nth directory (counting from the
left side of the list printed by directories when invoked without options),
beginning with zero.
In the directory stack, ~-N expands the Nth directory (counting from the
right side of the list printed by directories when involved without options),
beginning with zero.
Startup scripts
To set the bash environment variables permanently, settings are added to
the initialization file placed in the home directory of the users account
$HOME/.bash_profile.
The script execution order is as follows:
1. /etc/profile
2. /etc/profile.d
3. ~/.bash_profile or $HOME/.bash_profile
These three files are used to customize the users environment and some
typical examples are:
Set PATH and PS1 (shell prompt) variables
Set default printer via PRINTER variable
Set default text editor via EDITOR variable
Using aliases
The bash shell environment can be customized by creating aliases which is
illustrated in table 2.3.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 44
Table 2.3: Aliases and their Purpose
Alias Purpose
C Clear the screen
Ports Lists all listening TCP/UDP (Transmission Control
Protocol/User Datagram Protocol) ports with the PID
(process ID) of the associated process.
Update Update and install the newest versions of all packages
currently installed on the Debian system.
Vi Run vim text editor instead of old vi.
Changing Bash prompt
Bash prompt is customized by editing PS1 variable. To display the current
prompt setting, you must enter:
Prompt$echo $PS1
You can set the value of PS1 to a string.
Example:
rahul@rahul-desktop:~$ PS1=your wish is my command :
your wish is my command :
When a number of backslash-escaped special characters are inserted, the
Bash shell allows prompt strings to be customized.
Setting shell options
The changes are made to the users Bash shell environment using set and
shopt commands. Both the set and shopt commands control numerous
values of variables controlling shell behavior.
To list the currently configured shell options, type the following command:
Prompt$set o
Shell variable option is set using the following syntax:
Prompt$set o variableName
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 45
Shell variable option is unset using the following syntax:
Prompt$set +o variableName
Setting system wide shell options
A system-wide profile file for the Bash shell by default is /etc/profile file. You
may force setting using this file for all the users. However, it is suggested to
use /etc/profile.d file under CentOS/Fedora/Redhat Enterprise Linux and for
all other distribution edit /etc/profile file.
For example, to set up a JAVA_HOME and PATH settings for all the users,
you must create /etc/profile.d/java.sh file and enter:
#!/bin/bash
export JAAV_HOME=/opt/jdk1.5.0_12
export PATH=$PATH:$JAVA_HOME/bin
Save and close the file and then setup executable permission:
Prompt# chmod +x /etc/profile.d/java.sh
2.4 Commonly Used Commands and Utilities
In normal Linux installation, we can find hundreds of commands and utilities
along with thousands of support files. In spite of their overpowering number
and often cryptic names and more cryptic options, several commands are
very useful. There are many scripts present throughout the system that
contain most of these commands. Some of the commonly used commands
are shown in table 2.4.
Table 2.4: Commands and their Functions
Command Function
Cd Change directory
Cp Copy files
File Determine a files contents
Ls List files or directories
Ln Make a link to a file
mkdir Make a directory
mv Move (rename) a file
rm Remove a file
rmdir Remove a directory
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 46
cat Display the contents of file
chgrp Change the group of a file
chmod Change the permissions (mode) of a file
chown Change the owner of a file
chattr Change advanced file attributes
lsattr Display advanced file attributes
find Find files and directories
zip Compress a file using Windows/DOS zip
unzip Uncompress a file using Windows/DOS zip
df Display free space
du Display disk usage
lpr Print files
lpq View the print queue
lprm Remove the print jobs
lpc Line printer control program
ps List processes
w List users processes
uptime View the system load, amount of time it has been
running, etc.
uname Print system information
hostname Print the systems hostname
Activity 1:
Write a shell script to display the files in the current directory, create a
directory, and change to that directory.
(Refer section 2.2.5 for detailed guidelines.)
Self Assessment Questions
13. Bash shell supports path name expansion using the ____________
technique.
14. The variables provided by Bash shell that are prefixed with ~ are called
__________________.
15. ~+ is used as a shortcut to obtain the value of the PWD variable which
includes the current working directory. (True/False)
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 47
16. Which among the following is the command that displays advanced file
attributes? (Pick the right option)
a) lsattr
b) mkdir
c) chattr
d) lpr
2.5 Summary
Let us recapitulate the important concepts discussed in this unit:
A command interpreter program that provides interface between some
users and the operating system is referred to as the shell.
Linuxs built-in programming features help to automate recurring tasks
and create simple interactive applications.
The Free Software Foundation developed a replica of the Bourne shell,
written from scratch, termed as Bash (the Bourne-Again Shell).
Bash Startup scripts are the scripts of commands executed at login to
create an environment.
Bash shell provides debugging options which may be turned on or off
with the set command.
Linux creates parameter shell variables which are used to configure the
user shell.
Variables are used to store data and configuration options.
Functions and variables are exported to child processes using export
command.
A shortcut to commands is alias and the alias command is used to
display the list of all defined aliases.
The method of changing abbreviations to the directory names that they
stand for is Tilde expansion.
There are numerous commands and utilities along with thousands of
support files in normal Linux installation.
2.6 Glossary
Child process: A process created by another process (the parent process).
Debian system: It is a free operating system for your computer that uses
the Linux kernel.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 48
Noclobber: It is a feature that prevents the user from accidentally
overwriting the original file.
Sanity check: A process of checking that the output of a program produces
the expected output and not incorrect outputs due to careless programming.
Shopt command: A command used to set shell option or unset shell option
on Linux system.
Vi and emacs: These are two most popular, powerful, and difficult editors
which have syntax highlighting to make writing code easy.
2.7 Terminal Questions
1. What are the features that Bash shell provides?
2. What are the components of the Linux user environment?
3. Explain briefly the shell variables and their environment.
4. What are the rules for naming variables?
5. Explain briefly the three types of quotes.
6. Explain briefly the Tilde expansion.
7. List any ten commonly used commands along with their functions.
2.8 Answers
Self Assessment Questions
1. Buffer
2. Internal and external commands
3. False. Linux desktop is collection of different software applications.
4. c) zsh
5. Bang
6. chmod ug = rx script.sh
7. True.
8. Keywords
9. b) HOSTNAME
10. False. When allotting value to variable, do not put spaces on either side
of the equal sign.
11. Backslash
12. Read command
13. Curly brace
14. Tilde expansions
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 49
15. True
16. a) lsattr
Terminal Questions
1. Some of the basic features that Bash shell provides are input/output
redirection, a built-in command created for writing shell programs,
command-line editing via the command syntax of either vi or emacs,
arrays and arithmetic expressions. For more details, refer sub-section
2.2.1.
2. Linux user environment is composed of some components and those
include Kernel, shell, terminal emulator, and Linux desktop and
Windows manager. The shell serves as an interface between the kernel
and the user. For more details, refer sub-section 2.2.3.
3. Linux creates certain parameters for your login shell when the user logs
in. These parameters can be in the form of features or variables. Linux
provides a predefined set of variables for both system and shells use
and these variables are allocated system values, which in effect create
parameters. For more details, refer section 2.3.
4. The rules for naming variables are the variable name must always begin
with alphanumeric character or underscore character (_) that is followed
by one or more alphanumeric or underscore characters. For more
details, refer sub-section 2.3.1.
5. The three types of quotes are the double quote, the single quote, and
the backslash. Double quotes are represented as , single quote is
represented as , and the backslash is represented as \. For more
details, refer sub-section 2.3.1.
6. The Tilde expansions serve as synonyms for contents of other variables
with the users shell. Tilde expansion is pertinent to the ~ plus
characters including +, -, and N (integer) up to a slash. It is also used to
expand numerous specific pathnames. For more details, refer sub-
section 2.3.3.
7. Ten commonly used commands are cd used to change directory, file
used to determine a files contents, rmdir used to remove a directory,
chmod used to change the permissions (mode) of a file. For more
details, refer section 2.4.
-
Linux Operating System Unit 2
Sikkim Manipal University Page No: 50
References:
Blum, R., & LeBlanc, D. (2009). Linux FOR DUMMIES, 9th ed. NJ: Wiley
Publishing, Inc.
Johnson, C.F.A. (2009). Pro Bash Programming. New York: Springer
Verlag.
Petersen, R. (2008). Linux: The Complete Reference, 6th Ed. New York:
The McGraw-Hill Companies.
Siever, E., Figgins, S., Love, R., & Robbins, A. (2009). Linux in a
Nutshell, 6th ed. CA: OReilly Media, Inc.
E-References:
http://bash.cyberciti.biz/guide/Rules_for_Naming_variable_name
Retrieved on Dec 15, 2011.
http://ezinearticles.com/?Important-Concepts-For-Linux-Beginners---
Shells-and-Utilities&id=1558832 Retrieved on Dec 15, 2011.
http://linux-tutorial.info/modules.php?name=MContent&pageid=30
Retrieved on December 15, 2011.
http://lowfatlinux.com/linux-shell-script.html Retrieved on December
15, 2011.
http://sebug.net/paper/os/linux/Linux%20Shell%20Scripting%20Tutorial
%20v2.0.pdf Retrieved on December 15, 2011.
http://www.thegeekstuff.com/2010/06/bash-tilde-expansion/ Retrieved
on December 15, 2011.
top related