đ Link to the Room
đ Link for further learning
đˇď¸ Table of Contents
- Our first simple bash scripts
- Variables
2.1 Debugging Bash scripts
2.2 Using multiple variables - Parameters
3.1 Command-line parameters
3.2 Interactive input withread
3.3 Special Parameters in Bash - Arrays
4.1 Indexes
4.2 Creating an array in Bash
4.3 Printing all items in an array
4.4 Accessing a single item
4.5 Removing an item from an array
4.6 Changing (replacing) an item - Conditionals
5.1 if statement
5.2 Common comparison operators
5.3 Using parameters in conditionals
5.4 Checking files with conditionals
đ Study Notes
- Bash is a scripting language that runs within the terminal on most Linux distros, as well as MacOS.
- Shell scripts are a sequence of bash commands within a file, combined together to achieve more complex tasks than simple one-liner and are especially useful when it comes to automating sysadmin tasks such as backups.
Our first simple bash scripts
- Every bash script needs a starting line
- A bash script must start with this line:
#!/bin/bash - This tells your system: âRun this file using Bash.â
- Without it, the system wonât know how to execute your script.
- A bash script must start with this line:
- Your first example: printing text
- You can make Bash print text to the terminal using echo.
- Example:
echo "Hello World" - When you run the script, it will display:
Hello World - Think of echo like print in Python â it just shows text on the screen.
- You can run normal Linux commands in scripts
- Any command you can run in the terminal can also go inside a bash script.
- For example:
ls - When the script runs, it will list the files in the current directory â just like typing ls directly into the terminal.
- You can even combine commands, like
whoamiorid= This will show your current username and your user and group IDs
- Making the script runnable
- Before you can run your script, you must give it permission:
chmod +x yourfile.sh - Then run it with
./yourfile.sh - The ./ means ârun this file from the current directory.â
- Before you can run your script, you must give it permission:
- Always include #!/bin/bash at the top of your script (even if examples donât show it)
- Basic Linux command knowledge is assumed
- The best way to learn Bash is by running the commands yourself and experimenting
âWhat piece of code can we insert at the start of a line to comment out our code?
#
âWhat will the following script output to the screen, echo âBishBashBoshâ
BishBashBosh
Variables
-
A variable is just a name that stores a value, so you can reuse it later.
- In Bash, you create a variable like this:
name="Jammy" - Important rules: No spaces around
=and variable names canât contain spaces
- To use a variable, you add $ in front of its name.
- Hence
nameis the variable and$nameis the value stored inside it
- Variables help you avoid repeating the same text over and over, change values in one place instead of many and/or make scripts easier to read and fix
- Instead of typing âJammyâ everywhere, you just use $name.
Debugging Bash scripts
- Debugging means finding and fixing mistakes and Bash gives you tools to help.
- From terminal you can run your script in debug mode by
bash -x file.sh -
This shows each command as it runs, what works, where errors happen which is great for understanding what your script is actually doing step by step.
- You can turn debugging on and off inside your script:
-
This is useful when you only want to debug a specific part.
- When debugging
+means the command ran - The output shows what the command produced. - Errors are easy to spot because you can see exactly where things break
- This makes fixing mistakes much less frustrating.
Using multiple variables
- Youâre not limited to just one variable, e.g.
echo "Hello $name, welcome back!" - Bash will replace $name with its value automatically.
âWhat would this code return?
Jammy is 21 years old
âHow would you print out the city to the screen?
echo $city
âHow would you print out the country to the screen?
echo $country
Parameters
- Parameters are one of the most powerful parts of Bash.
- They let your script receive information from the outside, instead of hard-coding everything.
- Think of them as inputs to your script.
Command-line parameters
- When you run a bash script, you can pass values to it like this:
./example.sh Alex - Inside the script
$1is first argument,$2second argument,$3third argument, and so onâŚ
Interactive input with read
- Sometimes you donât want to pass values in the command line, instead, you want the script to ask the user for input.
- You can do this with
read:
- When the script runs, it will pause and wait for you to type something.
- Once you press Enter, it stores the input in the variable and prints it.
Special Parameters in Bash
| Parameter | **Description | Usage |
|---|---|---|
| $0 | tells you which script is currently running | writting usage messages; debugging; logging which script ran |
| $# | tells you how many arguments were passed to the script | useful for checking if the user passed enough arguments |
| $@ | all arguments passed to the script, one by one | commonly used in loops |
| $* | similar to $@, but it treats everything as one big string | recommended to avoid it unless you know why you need it |
| $? | exit status of last command, if either succeeded or failed | for error handling, automation, security scripts |
| $$ | gives the PID of the running script | for logging, temporary files, process tracking |
âHow can we get the number of arguments supplied to a script?
$#
âHow can we get the filename of our current script(aka our first argument)?
$0
âHow can we get the 4th argument supplied to the script?
$4
âIf a script asks us for input how can we direct our input into a variable called âtestâ using âreadâ
read test
âWhat will the output of âecho $1 $3â if the script was ran with â./script.sh hello hola alohaâ
hello aloha
Arrays
- Arrays let you store multiple values inside one variable instead of creating lots of separate variables.
- Think of an array like a numbered list.
- Most commonly notated as
var[index_position]
Indexes
- Every item in an array has a number called an index.
- Indexes always start at 0
- e.g.:
['car', 'train', 'bike', 'bus']
Creating an array in Bash
- Rules:
- Variable name first
- Items go inside parentheses
( ) - Items are separated by spaces
- Quotes are recommended
- e.g.:
transport=('car' 'train' 'bike' 'bus')
Printing all items in an array
echo "${transport[@]}"- this means @ is all items and
${}tells bash youâre working with variable - output:
car train bike bus
Accessing a single item
echo "${transport[1]}"- output:
train - Because Index
1= second item
Removing an item from an array
- To delete an item use
unset transport[1] - This removes
trainfrom the array. - If you print the array again, it will be gone.
Changing (replacing) an item
- You can assign a new value to a specific index by
transport[1]='trainride' - Now the array becomes
car trainride bike bus
Arrays are great when you need to store multiple values of the same type, loop through data, organize inputs
cleanly, build more advanced scripts (automation, security checks, etc.)
Extend your biography maker:
- Store multiple names in an array
- Store multiple facts (age, job, hobby)
- Pick and display them dynamically
- This is exactly how real scripts evolve â small upgrades over time
Â
âWhat would be the command to print audi to the screen using indexing.
echo "${cars[1]}"
âIf we wanted to remove tesla from the array how would we do so?
unset cars[3]
âHow could we insert a new value called toyota to replace tesla?
cars[3]='toyota'
Conditionals
- A conditional means that âOnly do this if something is true.â
- Bash checks conditions using operators like
equal to,greater than,less than
if statement
- Every if statement in Bash follows this pattern:
- IMPORTANT: You must have spaces inside
[ ]andfiends the if statement (itâsifbackwards)
Example:
Whatâs happening:
$countis compared to10-eqmeans âequal toâ- Since 10 = 10, it prints:
Common comparison operators
| operator | definition |
|---|---|
| -eq | equal to |
| -ne | not equal to |
| -gt | greater than |
| -lt | less than |
| -ge | greater than or equal to |
Using parameters in conditionals
- You can compare user input too.
- Run it like this:
./example.sh guessme(output will be `They are equal) - Run it with something else like:
./example.sh hi(output will be `They are not equal)
Checking files with conditionals
- Conditionals are very powerful for working with files.
- Two important file checks:
-f- does the file exist?-w- is the file writable?
âWhat is the flag to check if we have read access to a file?
-r
âWhat is the flag to check to see if it's a directory?
-d