Bash Basics
General Tips
Always start script with #!/bin/bash
Give the script run permissions using chmod +x script.sh
Each line is a new command that will be ran
Variables
Variables can be set using:
Variables can be retrieved using $varname
:
Script parameters
Parameters are stored in variables $1, $2, $3, ...
To get the number of parameters, use $#
User Input
User input can be taken using the read varname
command and the value taken can be retrieved like any other variable using $varname
. EX:
Arrays
Arrays in Bash are 0 indexed.
You can create an array using arrayname=('elm1' 'elm2' 'elm3' 'elm4')
You can then access an element of the array with $arrayname[index]
If you want to print out all elements of the array, you can do so with: echo "${arrayname[@]}"
if we want to remove or update a element in the array, we can do unset arrayname[index]
or arrayname[index]='value'
Array Cheatsheet:
Conditionals
Stolen From TryHackMe: https://tryhackme.com/room/bashscripting
-eq or =
Checks if the value of two operands are equal or not; if yes, then the condition becomes true.
-ne
Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true.
-gt
Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.
-lt
Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.
-ge
Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.
You can check multiple conditions using:
For Loops
Loop through an range of values with:
Or you can use a more familiar style:
Loop through an array:
Infinite Loop taken from: https://www.geeksforgeeks.org/bash-scripting-for-loop/
Last updated