|
CS469/569 - Linux and Unix Administration and Networking
Spring 2022
| Bash Scripting - Part 2
Parameters / variables:
By default variables are strings, but can be declared with the "declare "
builtin to be 64 bit ints (-i ), single dimensional arrays (-a ), or associative
arrays (-A ).
Variables are declared with name= [value]. If no value is specified, the
default is the empty string.
let expression [expression...]
- Defines integer variables, performs C like arithmetic expressions.
readonly variable
declare -r variable
- built-ins that make the variables read-only.
local expression
- makes variables local to a function, otherwise variables are global by default.
Arrays:
name[ index]= [value]
name=( values... );
Examples
x="string";
declare -i n=1235;
let n=5;
let n++;
declare -a a=("a" "b" "c");
a[0]="a";
declare -A aa=([a]="v1" [b]="v2")
aa[a]="v1";
Environment variables:
Each process maintains a set of variables called the environment, these
are name/value pairs (strings only.)
In bash, variables that you want in the environment are "exported" using
the 'export ' built-in. i.e.:
export PATH=$PATH:.
Environment variable commands
> printenv [name]
> env
- Displays the current environment.
> unset [-vf ] [name ...]
- unset the variable (default or
-v ) or function (-f ).
- read-only vars cannot be unset.
Special variables:
|
|
$? |
Status of last command executed |
$# |
# of positional parameters (like C's argc ) |
$0 , $1 , etc |
Positional parameters (like C's argv ) |
IFS |
Internal Field Separator, defines the word-splitting characters for a number of things in bash (such as the read built-in) |
$* |
Expands pos. params (starting at 1), separated by first char of IFS . |
$@ |
Expands pos. params (starting at 1), into separate words if quoted. Use $@ over $* when in doubt. |
$$ |
Process ID of the current shell |
$! |
PID of the last job put into the background |
RANDOM |
A random number between 0 and 32767, setting sets the seed. |
PATH |
Directory paths, separated by colons (: ), representing the directories to search for an executable. |
Bracket and variable expansions:
|
|
{ n.. m} |
Expands from n to m |
{ n.. m.. inc} |
Expands from n to m incrementing by inc. |
$ var |
Expands var |
${ var} |
" |
${ var[ index]} |
Expands the element of var |
${ var[*]} |
Expands in the same way as $* |
${ var[@]} |
Expands in the same way as $@ |
${# var[*]} |
Expands to # of elements in var (an array) |
${! asvar[*]} |
Associative array keys |
${ var:- word} |
Use word as a default if var is unset or null |
${ var:= word} |
Assign word if var is unset or null |
${ var:? word} |
Display error word if var unset or null |
${ var: offset} |
sub-string from offset to end of string |
${ var: offset: length} |
sub-string starting at offset of length length |
${ var# word} |
remove prefix matching pattern word, # = remove shortest match |
${ var## word} |
Like above, ## = remove longest match |
${ var% word} |
remove suffix pattern, % = remove shortest match |
${ var%% word} |
Like above, %% = remove longest match |
${ var/ pattern/ string} |
Replace pattern with string |
${ var^ pat} |
Convert uppercase matching pat, ^ = shortest match |
${ var^^ pat} |
Same as above, ^^ = longest match |
${ var, pat} |
Convert lowercase matching pat, , = shortest match |
${ var,, pat} |
Same as above, ,, = longest match |
- null pat matches all characters.
Command and arithmetic expansion:
$( command)
or
`command`
- command substitution. The output of command is substituted for the expansion.
$(( expression ))
- arithmetic expansion. Evaluates the expression as if it were a C arithmetic
expression. Supports most C operators.
Functions:
Functions are like self-contained "scripts", i.e. arguments to the function
are the positional parameters ($1 .. $ n), and they return an integer exit
value (via return .)
function name {
...
}
name () {
...
}
- Variables used in functions are global unless declared local.
Loops:
while list; do list; done
until list; do list; done
for name [ [ in [ word ...] ] ; ] do list ; done
- Basically a foreach type loop, places words into variable one at
a time. If [in <words...>] are omitted it iterates over the positional
parameters.
for (( expr1; expr2; expr3 )) ; do list ; done
- C style loop, each of the expressions are C arithmetic expressions. You can
use
{} 's in lieu of do and done when using this kind of loop.
break [n];
continue [n];
Conditionals:
if list; then list;
[elif list; then list; ] ...
[else list; ]
fi
case word in [ [( ] pattern [ | pattern] ... ) list ;; ]
...
esac
select name [ in word ]; do
list ;
done
Bash Builtins:
alias name=' value'
- Creates an command alias. is expanded (replaced with) .
bg [job specifier]
- Continues a stopped process in the background.
fg [job spec]
- Brings a job to the foreground.
jobs
- Lists jobs, both running and stopped.
echo [strings]
- Prints to the output, or a newline if strings is omitted.
printf [-v var] format [arguments]
- Like the C printf function
-v var assigns output to a variable.
read [-p prompt] [-s ] [-n nchars] names
- Reads a line of text and splits it according to IFS and assigns words the
variables listed.
-p prompt - Print a prompt before reading input
-s - Do not echo input characters
-n nchars - Stop after reading n characters.
... Many more options.
test
- Same as
[ ...] and mostly [[ ...]] , use "help test " in bash to list
file operators, such as:
if [[ -f <file> ]]; then echo "is a regular file"; fi
source file [params]
or
. file [params]
- Reads and executes in the current shell. Use
source not . (dot)
as it is less confusing that way.
|