Loops
|
A for loop repeats commands once for every thing in a list.
Every for loop needs a variable to refer to the thing it is currently operating on.
Use $name to expand a variable (i.e., get its value). ${name} can also be used.
Do not use spaces, quotes, or wildcard characters such as ‘*’ or ‘?’ in filenames, as it complicates variable expansion.
Give files consistent names that are easy to match with wildcard patterns to make it easy to select them for looping.
Use the up-arrow key to scroll up through previous commands to edit and repeat them.
Use Ctrl+R to search through the previously entered commands.
Use history to display recent commands, and !number to repeat a command by number.
|
Shell Scripts
|
Save commands in files (usually called shell scripts) for re-use.
bash filename runs the commands saved in a file.
$@ refers to all of a shell script’s command-line arguments.
$1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.
Place variables in quotes if the values might have spaces in them.
Letting users decide what files to process is more flexible and more consistent with built-in Unix commands.
|
Flow Control
|
The basic conditional structure in Bash is built as: if…then…else…fi .
Bash has operators specific for string and integer comparisons.
Bash also has comparison operators useful to test the existance of files and directories.
|
Arithmetic and Arrays
|
Bash is an untyped language. This means that all variables are stored as strings.
The $(( )) construct is used to create arithmetic operations
Bash arrays are created byi enclosing the elements within a pair of brackets, ( )
We can find the size of a Bash array with the construct ${#ArrayName[@]}
|
Functions and External Tools
|
Functions help us pack a set of operations with a single label.
Generally, Bash functions do not return values.
The output of Bash commands like cat, ls or find can be assigned to a Bash variable using the construct VAR=$(command)
|