0% found this document useful (0 votes)
179 views

Chapter 1 - Advanced Shell Features

Shell variables allow programs and shells to store and access named values. Variables must start with a letter or underscore and can contain letters, numbers, and underscores. Variables are assigned values using an equal sign and values containing spaces should be quoted. The PATH variable stores a list of directories searched to find and execute commands. Shell history and aliases provide ways to recall and modify past commands.

Uploaded by

Vyk Dragostief
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
179 views

Chapter 1 - Advanced Shell Features

Shell variables allow programs and shells to store and access named values. Variables must start with a letter or underscore and can contain letters, numbers, and underscores. Variables are assigned values using an equal sign and values containing spaces should be quoted. The PATH variable stores a list of directories searched to find and execute commands. Shell history and aliases provide ways to recall and modify past commands.

Uploaded by

Vyk Dragostief
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

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.: EZ=1
• An existing variable can be exported to the environment:
export EZ
• A variable can be assigned and exported in one step: export
EY=2
• Environment variables can also be created by:
• declare -x EX=3
• typeset -x EW=4
Displaying Variables
• The set command displays all variables
• Using echo $variable_name displays any variable
named variable_name
• The following will display only environment:
– env
– export -p
– declare -x
– typeset -x
The unset command
• Using the unset command will delete a variable and the value
it refers to:
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
The PATH variable
• A command will be executed without using the PATH variable if
it is:
– builtin to the shell
– an alias
– a function
– given with an absolute path
– given with a relative path
The PATH variable
The PATH variable contains the following directories in CentOS
6.3 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/joe/bin A directory for the current user (joe) to place
programs. Typically used by users who create their
own scripts.
Executing outside the PATH
• To execute commands not contained in the directories that are
listed in the PATH variable:
1. The command may be executed by typing the absolute path to the
command.
2. The command may be executed with a relative path to the
command.
3. The PATH variable can be set to include the directory where the
command is located.
4. The command can be copied to a directory that is listed in the PATH
variable.
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 (joe) 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:
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:
PATH Scenario
• The my.sh script would execute with an absolute path of
/home/joe/my.sh or a relative path of ./my.sh:
PATH Scenario
• The directory /home/joe could be added to the PATH variable
to allow the script to execute:
PATH Scenario
• The script could be copied or moved into a directory that is
contained within the PATH, and then it can be executed:
Avoiding Existing Commands
• The best way to avoid naming your script the same as an
existing command is to use the type command:
The PS1 variable
• The PS1 variable determines the bash shell prompt:

• Backslash codes are used to display special information, such


as:

Code Meaning
\$ Show $ for ordinary user or # for root user
\u Show the user name
\h Show the host name
\W Show the working directory basename
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

HISTSIZE 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 store 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:
– HISTIGNORE='ls*:cd*:history*:exit'
– 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
• An alias provides another way to execute a command. They
can be used for the following:
• To provide a nickname for a command
• To provide a way to execute a command with specific options
set by default
• To provide a way to execute a series of commands
Alias Examples
• A nickname often is a shorter command than the original:
– alias c='clear'
• A command with options:
– alias grep='grep --color'
• To execute a series of commands, use the semicolon or pipe to
separate the commands:
– 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
The alias command
• To define a new alias use the syntax:
– alias new_alias='command -options… arguments..'
– 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:
– Precede the command with a backslash: \ls
– Use an absolute path to the command: /bin/ls
– Use a relative path such as: ../../bin/ls
• Use unalias to remove an alias from the shell. For example:
unalias ls
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:

• 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:
Function Scenario
• To make a persistent function, add it to a shell initialization file
like ~/.bashrc:
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:
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
exected. 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 ";".
Background Lists
• If you want your commands to execute in the background
asynchronously, then a list of commands to run in the
background can be constructed separated by the "&".
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
• The job number and PID can be used to send signals to control
the command while it runs by commands like kill
AND Lists
• AND lists are formed by a chain of commands separated by &&
• If the command of the left side of the && executes successfully,
then the command on the right side will execute, otherwise
execution stops
OR Lists
• OR lists are formed by a chain of commands separated by ||
• If the command of the left side of the || executes
unsuccessfully, then the command on the right side will
execute, otherwise execution stops
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:
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
– Login shell - when the login process starts a new shell
– 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. Most users use the ~/.bash_profile
This file also typically executes all files file which typically also executes the
ending in ".sh" that are found in the ~/.bashrc file (which in turn executes
/etc/profile.d directory. the /etc/bashrc file). Since the
The next file that is execute is either ~/.bash_profile file is under the control
the ~/.bash_profile, ~/.bash_login or of the user, the execution of the
~/.profile file. Note: the ~ character ~/.bashrc and /etc/bashrc files are
represents the user's home directory. controllable by the user (the user
remove 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 the administrator 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 • Local initialization files are stored in
the /etc/ directory and require the user's home directory ~, so a user
administrator privileges to modify may modify their own initialization
• A backup copy should be created files
before modifying any initialization file • Sourcing an initialization file executes
the file in the context of the user's
shell, and is a good way of testing.
• The command source 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 6.3 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 6.3

You might also like