L2v2 Chapter 01 PowerPoint

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

Chapter 1

Advanced Shell Features


LPIC Certification Note

● Many of the topics that will be covered in this unit were also
covered in the previous course for LPIC-101 exam preparation
because these topics are testable on both LPIC exams.
Shell Variables
Shell Variables
● A variable is a name or identifier that can be assigned a value.

● The shell and other programs can read the values of the variables

● Variables can hold a value like “0” or “sue”

● Variables can hold delimited list values like “Joe Brown” or


“/usr/bin:/bin:/usr/sbin:/sbin”
Shell Variables

● Assigned value by typing name of variable followed by “=“ and then


the value

● Variable names must start with a letter or underscore, and contain


only letters numbers or underscore characters

● Values which contain spaces or other characters which may be


expanded by the shell should be single or double quoted to prevent
unwanted expansion
Shell Variables

Valid Variable Assignments Invalid Variable Assignments

A=1 1=a

_1=a A-1=3

LONG_VARIABLE=’O K’ LONG-VARIABLE=‘WRONG’

Name=‘Jose Romero’ ‘user name’=anything


Shell Variables
● The bash shell and many commands use variables to provide a
means for an ordinary users to configure various preferences.

● Local variables can only be used by the shell and use lowercase
names by convention.

● Environment variables are available to the shell and commands


started from the shell and use uppercase names by convention.
Shell Variables

● By default, when a variable is assigned a value it is a local variable.


E.g.:
sysadmin@localhost:~$ VAR1=1

● An existing variable can be exported to the environment:


sysadmin@localhost:~$ export VAR1

● A variable can be assigned and exported in one step:


sysadmin@localhost:~$ export VAR2=2
Shell Variables

● Environment variables can also be created by using the declare and


typeset commands:

sysadmin@localhost:~$ declare –x VAR3=3

sysadmin@localhost:~$ typeset –x VAR3=4


Displaying Variables
● The set command displays all variables (local and environment).

● Using echo $variable_name displays any variable named


variable_name.

● The following will display only environment variables:


○ env
○ export –p
○ declare –x
○ typeset -x
The unset command
● Using the unset command will delete a variable and the value it refers to:
sysadmin@localhost:~$ variable_1=“This is a variable”
sysadmin@localhost:~$ echo $variable_1
This is a variable.
sysadmin@localhost:~$ unset variable_1

● If the shell option nounset is enabled with the set -o nounset command,
then referring to an unset variable will result in an unbound variable error:
sysadmin@localhost:~$ set -o nounset
sysadmin@localhost:~$ echo $variable_1 -bash: variable_1:
unbound variable
sysadmin@localhost:~$ set +o nounset
sysadmin@localhost:~$ echo $variable_1
The PATH Variable
The PATH Variable
● Provides a colon : separated list of directories to search to execute
commands given without an explicit path.

● Directories are processed from left to right, and first directory found
which contains the command to execute will be used and any others
remaining to the right will be ignored.

sysadmin@localhost:~$ echo $PATH


/home/sysadmin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:
/usr/games:/usr/local/games
The PATH Variable
● A command will be executed without using the PATH variable if it is:
o builtin to the shell

o an alias

o a function

o given with an absolute path

o given with a relative path


The PATH Variable
● The PATH variable may contain the following directories by default:
Directory Contents
/bin Contains the most fundamental commands that are essential for the
operating system to function.

/usr/bin Contains the majority of the commands that are available for regular
users to execute.

/sbin Contains the essential administrative commands.

/usr/sbin Contains the majority of the administrative command files.

/usr/local/bin Normally empty, but may have commands that have been compiled
from local sources.

/usr/local/sbin Normally empty, but may have administrative commands that have
been compiled from local sources.

/home/jamie/bin A directory for the current user (jamie) to place programs. Typically
used by users who create their own scripts. *Note that is usually not
recommended to use a first name for a username. Convention is to use
last name and first initial (i.e., ramirezj for the user Jamie Ramirez).
Executing Outside the PATH

● To execute commands not contained in the directories that are


listed in the PATH variable:
o The command may be executed by typing the absolute path to the command.

o The command may be executed with a relative path to the command.

o The PATH variable can be set to include the directory where the command is
located. (Administrative privilege required)

o The command can be copied to a directory that is listed in the PATH variable.
(Administrative privilege required)
Path Review

● An absolute path is when you specify the location of a file or


directory from the top level directory (called the root directory)
through all of the sub directories to the file or directory. Absolute
paths start with /.

● A relative path is when you specify the location of a file or directory


relative to the current directory. Relative paths do not start with /.
PATH Scenario
● A common scenario is a user, Josie Smith (smithj), creates a script
in their home directory and they make it executable, but when they
try to execute it, the shell can’t find it:
smithj@localhost:~$ cat my.sh
#/bin/bash
echo “Today is `date +%D`”
echo “Hello $Hello ${USER}tech”
smithj@localhost:~$ chmod u+x my.sh
smithj@localhost:~$ my.sh
-bash: my.sh: command not found
smithj@localhost:~$
PATH Scenario
● The my.sh script failed to execute with the error command not
found because the script is located in a directory that is not
contained in the PATH variable:
smithj@localhost:~$ my.sh
-bash: my.sh: command not found
smithj@localhost:~$ pwd
/home/ smithj
smithj@localhost:~$ echo $PATH
/usr/lib/qt-3.3/bin:/usr/local/bin:/bin/:/usr/bin:/usr/local/sbin:/usr/sbin:
/sbin:/home/smithj/bin
PATH Scenario
● The my.sh script would execute with an absolute path of
/home/smithj/my.sh or a relative path of ./my.sh:

smithj@localhost:~$ /home/smithj/my.sh
Today is 04/22/25
Hello josietech
smithj@localhost:~$ ./my.sh
Today is 04/22/25
Hello josietech
smithj@localhost:~$
PATH Scenario
● The directory /home/smithj could be added to the PATH variable to
allow the script to execute:
smithj@localhost:~$ echo $PATH
/usr/lib/qt-3.3/bin:/usr/local/bin:/bin/:/usr/bin:/usr/local/sbin:/usr/sbin:
/sbin:/home/smithj/bin
smithj@localhost:~$ PATH=$PATH:/home/smithj
smithj@localhost:~$ echo $PATH
/usr/lib/qt-3.3/bin:/usr/local/bin:/bin/:/usr/bin:/usr/local/sbin:/usr/sbin:
/sbin:/home/smithj/bin:/home/smithj
smithj@localhost:~$ ./my.sh
Today is 04/22/25
Hello josietech
smithj@localhost:~$

Note: This change would not survive a reboot.


PATH Scenario

● The script could be copied or moved into a directory that is


contained within the PATH, and then it can be executed:
smithj@localhost:~$ mv bin/my.sh .
smithj@localhost:~$ mv my.sh /home/josie/bin/
smithj@localhost:~$ ./my.sh
Today is 04/22/25
Hello josietech
smithj@localhost:~$
Avoiding Existing Commands

● The best way to avoid naming your script the same as an existing
command is to use the type command:
smithj@localhost:~$ type echo
echo is a shell builtin
smithj@localhost:~$ type hello
hello is a function
hello ()
{
echo hello
}
smithj@localhost:~$ type ls
ls is aliased to `ls –color=auto’
smithj@localhost:~$ type cal
cal is /usr/bin/cal
smithj@localhost:~$ type junk
-bash: type: junk: not found
The PS1 variable
● The PS1 variable determines the bash shell prompt:
sysadmin@localhost:~$ echo $PS1
[\u@\h \W]\$
sysadmin@localhost:~$ PS1=’\$ ‘
$ _

● Backslash codes are used to display special information, such as:


Code Meaning
\$ Show $ for ordinary user or # for root user
\u Show the username
\h Show the hostname
\W Show the working directory base name
History Variables
History Variables

● Several variables affect the way history is stored for the bash shell:
Variable Effect
HISTFILESIZE Number of history entries to store in history file.
HISTFILE Name of history file if different from ~/.bash_history.

HISTFILE Number of history entries to store in memory. If larger than


HISTFILESIZE, then only the most recent number of commands set
by HISTFILESIZE will be stored in the history file.
HISTCONTROL Controls which entries to exclude from history.
HISTCONTROL Variable
● The following values of the HISTCONTROL variable affect how history
is stored:
Value Effect
ignoredups Do not store duplicate commands that are executed
consecutively.
ignorespace Do not store a command preceded by a space.
ignoreboth Combination of ignoredups and ignorespace.

erasedups Delete previous history entry of duplicate command.

ignorespace:erasedups Combination of ignorespace and erasedups.


HISTIGNORE Variable
● The HISTIGNORE variable can be set with globbing patterns to
exclude commands from being stored in history

● For example:
o HISTIGNORE='ls*:cd*:history*:exit’

o The above means do not store any command that starts with ls, cd, or
history, as well as the exit command.
Setting Variables

● Variables assigned as the command prompt will only retain their


value while the user is logged in.

● For variables to retain their values persistently, they can be set


globally in the /etc/profile file by an administrator, or in the
~/.bash_profile file by an ordinary user.

● Recall ~ represents the user’s home directory.


Aliases
Aliases

● An alias provides another way to execute a command. They can be


used for the following:

o To provide a nickname for a command

o To provide a way to execute a command with specific options set by default

o To provide a way to execute a series of commands


Alias Examples

● A nickname often is a shorter command than the original:


sysadmin@localhost:~$ alias c=‘clear’

● A command with options:


sysadmin@localhost:~$ alias grep=‘grep --color’

● To execute a series of commands, use the semicolon or pipe to


separate the commands:
sysadmin@localhost:~$ alias which=‘alias | /usr/bin/which --tty-only --read-alias
--show-dot –show-tilde’
The alias Command
● Executing alias without any arguments displays the aliases that are
defined in the way that they could be entered as new aliases:

sysadmin@localhost:~$ alias
alias l.=‘ls –d .* --color=auto’
alias ll=‘ls –l –color=auto’
alias ls=‘ls –color=auto’
alias vi=‘vim’
alias which=‘alias | /usr/bin/which --tty-only –read-alias –show-dot –show-tilde’
sysadmin@localhost:~$
The alias Command
● To define a new alias use the syntax:
alias new_alias=‘command –options… arguments…’

o E.g. alias grep='grep --color'

● Aliases defined from the command line will not persist after the user
exits.

● Persistent global aliases are defined in /etc/profile or


/etc/profile.d/*.sh files.

● Persistent user aliases are defined in ~/.bashrc.


Avoiding Aliases
● Sometimes a user wants to avoid an alias.

● To avoid an alias like ls:


o Precede the command with a backslash: \ls
o Use an absolute path to the command: /bin/ls
o Use a relative path such as: ../../bin/ls

● Use unalias to remove an alias from the shell. For example:


sysadmin@localhost:~$ unalias ls
Functions
Functions

● Functions can be used like aliases as nicknames for commands,


although, they are usually used within scripts to work in more
advanced ways.

● To create a function, use the following syntax:


function_name () {commands_here}
Function Scenario
● You find yourself executing a series of commands repeatedly:
sysadmin@localhost:~$ cd /usr/share/doc
sysadmin@localhost:/usr/share/doc$ echo “Document directory usage report” >
/tmp/report
sysadmin@localhost:/usr/share/doc$ date >> /tmp/report
sysadmin@localhost:/usr/share/doc$ pwd >> /tmp/report
sysadmin@localhost:/usr/share/doc$ du -sh . >> /tmp/report

● A function could be defined which could execute these series of


commands for you.
Function Scenario
● Functions can be defined and executed on the command line:

sysadmin@localhost:/usr/share/doc$ report() {
> /usr/share/doc
> echo “Document directory usage report” > /tmp/report
> date >> /tmp/report
> pwd >> /tmp/report
> du -sh . >> /tmp/report
> }
sysadmin@localhost:/usr/share/doc$ report
Function Scenario
● To make a persistent function, add it to a shell initialization file like
~/.bashrc:
sysadmin@localhost:~$ cat .bashrc
# .bashrc
HISTCONTROL=‘ignorespace:erasedups’
# Source global definitions
if [ -f /etc/bashrc ]; then
./etc/bashrc
fi
# User specific aliases and functions
alias grep=‘grep --color’
report() {
cd /usr/share/doc
echo “Document directory usage report” > /tmp/report
date >> /tmp/report
pwd >> /tmp/report
du –sh . >> /tmp/report
}
Function Arguments

● Arguments can be passed to a function in a way similar to how they


are passed to commands

● The first argument passed to a function can be referred to as $1, the


second as $2, etc.

● Arguments can make a function much more flexible.


Function Argument Scenario
● Arguments can make a function more flexible, like allowing the directory to
be specified:
sysadmin@localhost:/usr/share/doc$ type report
report is a function
report ()
{
cd $1;
echo “Document directory usage report” > /tmp/report;
date >> /tmp/report;
pwd >> /tmp/report;
du –sh . >> /tmp/report;
cd - > /dev/null;
cat /tmp/report
}
sysadmin@localhost:/usr/share/doc$ report /usr/share/fonts
Document directory usage report
Tue Apr 22 07:28:07 PDT 2025
/usr/share/fonts
21M
Lists
Lists
● In the context of the bash shell, a list is series of commands
separated by one or more of these operators:
Operator Meaning
; The commands within the list are executed sequentially where the shell will execute the first
command and wait for it to terminate before executing the next command. The exit status of the
list is based upon the exit status of the last command that is executed.

& Each command within the list is executed asynchronously within a subshell, or in the
background. The shell does not wait for the commands to terminate and returns an exit stats
of zero.
&& This is an “AND” list, so if the command on the left side of && executes successfully, then the
command on the right side of && will execute. The exit status of the list is based upon the exit
status of the last command that is executed.
|| This is an “OR” list, so if the command on the left side of || does not execute successfully,
then the command on the right side of || is executed. The exit status of the list is based upon
the exit status of the last command that is executed.
Sequential Lists

● If you want your commands to execute in series, one after another,


then a sequential list of commands can be constructed separated by
the semi-colon ; character:

sysadmin@localhost:/usr/share/doc$ date;who;uptime
Tue Apr 22 07:39:50 PDT 2025
student tty1 2025-04-22 02:50 (:0)
student pts/0 2025-04-22 02:50 (:0)
student pts/1 2025-04-22 02:50 (:0.0)
07:39:50 up 4:51, 3 users, load average: 0.00, 0.00, 0.00
Background Lists

● To execute commands in the background asynchronously, construct


a list of commands separated by the ampersand & character:

root@localhost:~$ updatedb&makewhatis&
[1] 4326
[2] 4327
Background Lists

● Commands that may run for a long time are especially appropriate
for background lists.

● For each background command that is executed, a job number in


square brackets and a process identifier (PID) are reported:
root@localhost:~$ updatedb&
[1] 4326

● The job number and PID can be used to send signals to control the
command while it runs by commands such as kill.
AND Lists

● AND lists are formed by a chain of commands separated by the


double ampersand && character.

● If the command of the left side of the && executes successfully,


then the command on the right side will execute, otherwise
execution stops.
sysadmin@localhost:~$ grep –q contractor /etc/passwd && echo contractor has account
contractor has account
sysadmin@localhost:~$
OR Lists

● OR lists are formed by a chain of commands separated by the double


pipe || character.

● If the command of the left side of the || executes unsuccessfully,


then the command on the right side will execute, otherwise
execution stops:
sysadmin@localhost:~$ grep –q clerk /etc/passwd || echo clerk has no account
clerk has no account
sysadmin@localhost:~$
Hybrid Lists
● Hybrid lists are lists that mix the list operators.

● Powerful combinations can be created by using hybrid lists, like


these AND/OR examples that act like if/then/else statements:

sysadmin@localhost:~$ grep –q alice /etc/passwd && echo alice has account || echo alice
has no account
alice has no account
sysadmin@localhost:~$ grep –q joe /etc/passwd && echo joe has account || echo joe has no
account
joe has account
Initialization Files
Initialization Files

● Initialization files are used to set the initial state of the shell's
variables, aliases, and functions.

● Global initialization files reside in the /etc/ directory, affect all


users, and can only be modified by an administrator.

● Local initialization files reside in the user's home directory (~),


affect only the user, and can be modified by the user.
Bash Initialization Files

● Each shell uses different initialization files.

● Different initialization files may be used:


o Login shell - when the login process starts a new shell.
o Interactive shell - when the user opens a new terminal or
executes bash.
Bash Initialization Files
Bash Initialization Files
● The /etc/profile file is executed first.
This file also typically executes all files
ending in .sh that are found in the
/etc/profile.d directory.

● The next file that is executed is either the


~/.bash_profile, ~/.bash_login or
~/.profile file.

Note: the ~ character represents the user's home


directory.
Bash Initialization Files
● Most users use the ~/.bash_profile file,
which typically also executes the
~/.bashrc file (which in turn executes
the /etc/bashrc file).

● Since the ~/.bash_profile file is under


the control of the user, the execution of
the ~/.bashrc and /etc/bashrc files are
controllable by the user.

○ The user removes the line that


executes the ~/.bashrc file.
Bash Initialization Files
File Purpose
/etc/profile This file can only be modified by the administrator and will be
executed by every user who logs in. Administrators use this
file to create key environment variables, display messages to
users as they log in and set key system values.

~/.bash_profile Each user has their own .bash_profile file in their home
directory. The purpose for this file is the same as the
/etc/profile file, but having this file allows a user to
customize the shell to their own tastes. Normally used to
create customized environment variables.

~./bashrc Each user has their own .bashrc file in their home directory.
The purpose for this file is to generate things that need to be
created for each shell, such as local variables and aliases.

/etc/bashrc This file may affect every user on the system. Only
administrators can modify this file. Like the .bashrc file, the
purpose for this file is to generate things that need to be
created for each shell, such as local variables and aliases.
Modifying Initialization Files
● Global initialization files are stored in the /etc/ directory and require
administrator privileges to modify.

● A backup copy should be created before modifying any initialization file.

● Local initialization files are stored in the user's home directory ~, so a user
may modify their own initialization files.

● Sourcing an initialization file executes the file in the context of the user's
shell, and is a good way of testing.

● The source command and . are synonyms.


Bash Exit Files
● Just as bash executes certain files when it starts up, bash will execute
certain files if they exist when you exit the shell.

● If the .bash_logout file is located in the user's home directory, then it will
be executed upon logout

● The default ~/.bash_logout from CentOS executes the clear command to


remove any text from the screen.

● If the /etc/bash_logout file exists then it will also be executed upon


logout.

● The /etc/bash_logout file does not exist by default in CentOS.

You might also like