Basic stuff
Loops
Here we didnāt do
Since the dollar sign before j causes it to be treated as a variable substitution, rather than an increment operation.
Functions
Just write
grep and sed
grep
The grep
command is used to search for patterns within files. It stands for āGlobal Regular Expression Print.ā
Basic Usage: grep [options] pattern [fileā¦] Options:
The sed
command is a stream editor used to perform basic text transformations on an input stream (a file or input from a pipeline).
CLI arguments
#: This symbol starts a comment in shell scripts.
if: Begins the conditional statement.
[ $# -ne 3 ]: Checks if the number of command-line arguments ($#) is not equal to (-ne) 3.
$# is a special variable that holds the number of positional parameters (i.e., command-line arguments) passed to the script.
-ne stands for "not equal."
The condition [ $# -ne 3 ] evaluates to true if the number of arguments is not 3.
Logical Operators
In shell scripting, logical operators are used to perform boolean operations (like AND, OR, and NOT) for condition evaluation. The following are the main logical operators used in shell scripting:
1. AND Operator
- Symbol:
&&
- Usage: Both conditions must be true for the entire expression to evaluate to true.
- Example:
2. OR Operator
- Symbol:
||
- Usage: At least one of the conditions must be true for the entire expression to evaluate to true.
- Example:
3. NOT Operator
- Symbol:
!
- Usage: Negates the value of a condition (true becomes false, and false becomes true).
- Example:
4. Combining Conditions
- You can combine multiple conditions using parentheses
()
and logical operators. - Example:
5. Conditional Operators for Integers
You often see integer comparisons combined with logical operators, such as:
-eq
: Equal to-ne
: Not equal to-gt
: Greater than-lt
: Less than-ge
: Greater than or equal to-le
: Less than or equal to
Example:
6. Conditional Operators for Strings
String comparison can also be combined with logical operators:
=
or==
: String equality!=
: String inequality-z
: True if the string is null (empty)-n
: True if the string is not null (not empty)
Example:
Summary of Common Logical Operators:
Operator | Description | Example Usage |
---|---|---|
&& | Logical AND | [[ $a -gt 10 && $b -lt 20 ]] |
` | ` | |
! | Logical NOT | [[ ! $a -gt 10 ]] |
-eq | Integer equality | [[ $a -eq $b ]] |
-ne | Integer inequality | [[ $a -ne $b ]] |
-gt | Greater than (integers) | [[ $a -gt 10 ]] |
-lt | Less than (integers) | [[ $a -lt 10 ]] |
-ge | Greater than or equal to (integers) | [[ $a -ge 10 ]] |
-le | Less than or equal to (integers) | [[ $a -le 10 ]] |
== | String equality | [[ $str1 == "hello" ]] |
!= | String inequality | [[ $str1 != "world" ]] |
-n | String is not null (not empty) | [[ -n $str ]] |
-z | String is null (empty) | [[ -z $str ]] |
These logical operators are used in if
, while
, until
, and test
conditions to control the flow of shell scripts.