Bash is a powerful scripting language used in the Linux terminal to automate tasks and perform various operations. Here are some essential commands and concepts to help you get started with Bash scripting.
Create a file name whatever you want. But, make sure it ends with .sh. Open that file in your favorite text editor and write the first line to begin your shell script journey.
_10#! /bin/bash
The #! /bin/bash line is called the shebang or hashbang, and it is used to specify the interpreter to be used for executing the script. In this case, #!/bin/bash indicates that the script should be interpreted and executed using the Bash shell.
Open your terminal and go to the directory where you created the script file. Then run the below command to execute the script
_10./my_script.sh
At this stage, you won't see any output since we have not written anything. Let's add some fun stuff.
You can use the echo command to print statements or messages in the terminal. For example:
_10echo Hello World
You will see Hello World in your terminal
You can assign values to variables in Bash using the assignment operator (=). Variable names are usually uppercase by convention and can contain letters, numbers, and underscores. Here's an example:
_10NAME="Kite"_10echo "My name is $NAME"
To read user input in Bash, you can use the read command. It prompts you to enter a value and stores it in a variable. For example:
_10read -p "Enter your name: " NAME_10echo "Hello $NAME, nice to meet you!s"
Gives you the following output.
_10Enter your name: Kite_10Hello Kite, nice to meet you!s
Bash supports various conditional statements to control the flow of your script. Here are a few examples:
_10if [ "$NAME" == "Kite" ]_10then_10 echo "Your name is Kite"_10fi
_10if [ "$NAME" == "Kite" ]_10then_10 echo "Your name is Kite"_10else_10 echo "Your name is not Kite"_10fi
_10if [ "$NAME" == "Kite" ]_10then_10 echo "Your name is Kite"_10elif [ "$NAME" == "Jack" ]_10then_10 echo "Your name is Jack"_10else_10 echo "Your name is NOT Kite or Jack"_10fi
Below is an example of comparing two numbers using -gt operator in the shell script
_10NUM1=3 _10NUM2=5_10if [ "$NUM1" -gt "$NUM2" ] _10then _10 echo "$NUM1 is greater than $NUM2"_10else _10 echo "$NUM1 is less than $NUM2"_10fi