Objectives:
- Explain the features and capabilities of bash shell scripting.
- Know the basic syntax of scripting statements.
- Be familiar with various methods and constructs used.
- Test for properties and existence of files and other objects.
- Use conditional statements, such as if-then-else blocks.
- Perform arithmetic operations using scripting language.
The return value of a script is stored in the environment variable represented by $? A non-zero value represents failure, while a zero value represents success.
Special characters used in bash scripts:
- # – comment
- \ – continuation on a new line; splitting long commands on multiple lines
- ; – what follows is a new command to be executed
- $ – indicate a variable
- > – redirect output
- >> – append output
- < – redirect input
- | – pipe result into the new command
- && – abort subsequent commands when an earlier one fails
Typing help in the shell, will display the built-in commands and help.
Script parameters are depicted by the $ followed by a number.
- $0 – script name
- $1 – 1st argument
- $2, $3 – 2nd, 3rd argument
- $* – all arguments
- $# – number of arguments
Command substitution
- by enclosing the inner command in $( ) – prefered form
- by enclosing the inner command with backtick ( ` ) – deprecate form
$ ls /lib/modules/$(uname -r)
Environment Variables
Standard environment variables:
- PATH
- HOME
- HOST
Print a list of environment variables with printenv or env.
$ printenv $ env
Set environment variables with the set command.
Variables can be exported from a local variable to a global (environment) variable using the export keyword.
$ export VAR=value # or # VAR=value; export VAR
Typing just export without any arguments will show all the exported environment variables.
Functions
Declaration of a function:
function_name () { command ... }
Example of a function named display.
display () { echo "This is a sample function" }
If statement
if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi or if condition then statements else statements fi
File condition expressions can be viewed with man 1 test command.
Boolean Expressions
- && – AND
- || – OR
- ! – NOT