Shell / bash scripting
Shell is a commands interpreter. Implementations: sh, bash, zsh etc.
Variables
Conditional statements
Passing arguments to script
Read user input
Loops
Functions
#!/bin/sh
- shebang line. Tells OS what shell program to use to execute script file.
/bin/sh - actual location of the program.
Variables example
Conditional statement example
Passing arguments to script
Then we can run script in terminal: ./script.sh value1 value2
In this way we can provide up to 9 parameters.
$* - can be used to represent all arguments as a string. $# - total number of arguments provided.
Read user input
read -p - read from the prompt. Store input to the user_name variable.
Loops
$(( ))
- double parenthesis for arithmetic operations.
Also in if statement we can see double brackets [[ ]]
instead of single brackets.
[]
- POSIX. [[ ]]
- BASH. Bash variant has more features, but we loose portability.
Functions
Function without parameters
Function with parameters and return value
$?
- captures value returned by last command.
Bash best practices
Last updated
Was this helpful?