🍕Linux Scripting

Notes on Linux scripting with #!/bin/bash from TryHackMe.com

Creating script file:

nano first_script.sh

Start every script with shebang like this:

#!/bin/bash

Before running a script for the first time:

1) Give it permission by:

chmod +x first_script.sh

2) To run the script add ./

./first_script.sh

Variables

# Defining the Interpreter 
#!/bin/bash
echo "Hey, what’s your name?"
read name
echo "Welcome, $name"

The script above displays a string on the screen: "Hey, what’s your name?” This is done by echo command. The second line of the script contains the code read name. read is used to take input from the user, and name is the variable in which the input would be stored. The last line uses echo to display the welcome line for the user, along with its name stored in the variable.

Loops

The first line has the variable i that will iterate from 1 to 10 and execute the below code every time. do indicates the start of the loop code, and done indicates the end. In between them, the code we want to execute in the loop is to be written. The for loop will take each number in the brackets and assign it to the variable i in each iteration. The echo $i will display this variable’s value every iteration.

The IF statement

Comments

If the code is getting lengthy and complicated it's good practice to start adding comments

Putting all I've learned together into a simple locker script

Asks a user to input Username, Company name and a PIN. If all credentials are correct, shows the balance of gold coins

A Search Script

This script searches for a specific keyword in all the files (with .log extension) in a specific directory.

To run the script:

How to search the file:

Last updated