Linux Bash Scripting
Bash is a command-line interpreter or Unix Shell or Bash Scripting is used to automate the execution of the tasks so that humans do not need to perform them individually. Bash scripting is a great way to automate different types of tasks in a system.
Developers can avoid doing repetitive tasks using bash scripting.
Basics Bash Scripting
1. Create a Script File:
Open a terminal and type:
gedit hello.sh # Creates a file named "hello.sh"
2. Add Code:
#!/bin/bash: This is the shebang line that specifies the interpreter (/bin/bash) to be used for running the script.
Type these lines into the file:
#!/bin/bash # Tells the computer: "Use Bash to run this!" echo "Hello, World!" # Prints "Hello, World!" on the screen
3. Make It Executable:
Save the file, then type:
chmod +x hello.sh # Gives permission to run the script
4. Run It:
Use the below command to execute the script:
./hello.sh
File Names and Permissions
- Save the file with the .sh extension, so that the Linux system can execute it. - When we first create a file with the .sh extension, it doesn't have any execute permission and without the execute permission the script will not work. So, we should provide execute permission to it using the chmod command. - By convention, it is recommended to use snake case ( my_bash_script.sh ) or hyphens ( my-bash-script.sh ) for naming a script file.
Variables in bash
Example Script:
Name="SATYAJIT GHOSH" Age=20 echo "The name is $Name and Age is $Age"
Output of Variables:
The name is SATYAJIT GHOSH and Age is 20
Note: It is best practice to always use a local variable inside a function to avoid any unnecessary confusion.
Example Script:
#!/bin/bash
var1="Apple" #global variable
myfun(){
local var2="Banana" #local variable
var3="Cherry" #global variable
echo "The name of first fruit is $var1"
echo "The name of second fruit is $var2"
}
myfun #calling function
echo "The name of first fruit is $var1"
#trying to access local variable
echo "The name of second fruit is $var2"
echo "The name of third fruit is $var3"
Output of local and global variables:
The name of first fruit is Apple The name of second fruit is Banana The name of first fruit is Apple The name of second fruit is The name of third fruit is Cherry
Here in this above example, var2 is a local variable, so when we are accessing it from the function it is doing fine but when we are trying to access it outside the function, it is giving us an empty result in the output.
even though var3 is defined inside a function still it is acting as a global variable and it can be accessed outside the function.
Input and Output in bash
Resource:
Bash Scripting - Introduction to Bash and Bash Scripting - GeeksforGeeks