Ever been daunted by writing Bash scripts or using the terminal? Many developers prefer to use the graphical user interface (GUI) to navigate their files and applications on their computers. With Bash, developers on macOS and Linux operating systems (OS) can do lots of computer processes right from the terminal without ever having to use their mouse or the keyboard for interaction.
In this lesson, you'll learn how to write simple Bash scripts and how you can 10X your productivity efficiently.
What is Bash?
Bash, also known as Bourne Again Shell, is an interactive shell or command line interpreter popular with UNIX users. Therefore, what is a shell? A shell (command interpreter) is an interface between the user and the kernel. It is an executable text file that contains shell commands and other specific programming structures.
Some examples of shells include:
- Bourne
- Bash (Bourne Again Shell)
- Z Shell
- C Shell
Now, when do you use a Shell?
Bash scripting gives the user the power and control over the OS in the following ways:
- Monitoring the system
- Data backup and restoring
- Creating an alert system
- User administration and many more
Another use case of the CLIs is they can handle editing, creating, and deleting multiple files with one command. It is also possible to automate the everyday task and fetch web pages from the internet using the curl command.
If you do a task repeatedly, Bash can make such a task over within the shortest timeframe. Let's get started.
Creating Variables in Bash
Like in any other programming language, the Linux environment variables are constants for a memory location where a value is stored for the configuration and manipulation of the system and displaying additional system information based on the stored value.
Also, remember that Bash is a weakly typed programming language that doesn't allow you to define any data type in the variable declaration.
An example of the format of a variable is <NAME>=<VALUE>
Declare variables in Bash
To begin, let's start with writing some essential variables.
web_url="https://github.com/the-collab-lab"
distro="Kali Linux"
Call a variable
The way to call a declared variable in Bash is by using the echo command to print out the variable as an output. Run this command:
# referencing the value of the variable
echo $blog_post_url
# OR
echo ${blog_post_url}
If you decide you no longer need or want to remove the variable, run this command:
unset <name-of-the-variable>
# for example
unset blog_post_url
Environment Variables
These are standard global environment variables present in a UNIX Shell. Sometimes environment variables are regarded as exported variables.
- env : Listing all environment variables
- export: creating a new variable for the user
- printenv: Viewing the environment variables using the print command
- read: getting user input
View the Environment Variables
The env and printenv commands do similar things as they are responsible for allowing us to see the list or print all environment variables present. Type this in your terminal:
env
# OR
printenv
Result:
To view each of the environment variables using the print command, run:
printenv HOME // the env for HOME user directory
printenv SHELL PWD SESSION_MANAGER // print more than one environment variable
Create an Environment Variable
Using the export command, we can set a variable for the Linux environment variable. The rule of thumb when setting an environment variable is it is temporary.
export IP="80.0.0.1"
# Changing the path
export PATH=$PATH:~/script
To make this permanent, open and modify the .bashrc file. It is a hidden file; create one if it is not in your home directory. Add the previous export command.
Run this command:
vim ~/.bashrc
Edit this file and add the variable. Doing this will ensure the command is available for use by the system.
Since we are using Vim to edit the file, to exit and save the file, type:wq
To save the changes in the .bashrc file, run this command:
source ~/.bashrc
How to Read User Input
Getting user input in Bash is possible, like in JavaScript, Python, and other programming languages, using the read command to get the value from the user and print the output.
In your terminal, run this command:
read name
The command waits for the user to type their name in the terminal. Afterwards, type this command to get the user input:
echo $name // teri
Also, you can pass in multiple variable names with the read
command like this:
read name age city
Like the previous, you need to enter the result of the variable with spaces in between them:
Not supplying the read command with a variable name, the stored command read is stored as a pre-defined variable called $REPLY. Run this command:
read
// type your message as the program waits for you
echo $REPLY // result of the message
Displaying a message with the read command
To display a message to the user, include the -p
flag with the read command, including the variable name after the display message:
read -p "Enter your IP address: " ip
echo $ip
Hide sensitive information
The read command is versatile as it can also hide sensitive information from displaying in the terminal as you type. To achieve this, run this command with the -s command:
read -s -p "Enter password: " passwd
echo $passwd
Creating Your First Script with Bash
Running bash script helps with automation and makes the life of developers easier.
For this example, we will create bash scripts that create a new folder, print out a message within the file, list the folder structure, and ultimately read the file by displaying the message in the file.
Create a folder in your home directory using the terminal, of course, and navigate into the folder.
mkdir scripts
cd scripts
Using Vim, run this command to create the file for the script with the .sh extension:
vim file_script.sh
To enable the insert mode, press the i
button.
Copy and paste these lines of code:
#!/bin/bash
mkdir -p dir1
echo "hello, bash world! writing my first script" > dir1/file.txt
tree .
cat dir1/file.txt
At the top of the file, the “shebang” denoted by #! instructs the operating system to run the script with the /bin/bash executable.
Save and exit the interactive shell with this command :wq. Before then, ensure to press the esc key.
Since shell scripts are executable files, you need permission to run this file from the owner with this command:
chmod 700 name-of-file
chmod 700 file_script.sh
Also, you can use this command as well to enable all users to run the script:
chmod +x file_script.sh
Before running the script and seeing the action, install the tree
command:
// on macOS using brew
brew install tree
// on Ubuntu
sudo apt install tree
The tree
installation will display directories as trees.
Now, let’s run the script using path:
# relative path
./file_script.sh
Alternatively, you can use the absolute path to run the bash script from the specified folder:
/home/teri/Desktop/scripts/file_script.sh
Also, you can run it with the bash keyword:
bash file_script.sh
If you run it with the absolute path or the bash keyword, you do not need to grant permission to the executable script.
Finally, to make the script executable from any path and folder in the terminal, edit the .bashrc file and include this:
export PATH="$PATH:~/Desktop/scripts"
Save and quit the .bashrc file by pressing the esc key and using the :wq. Also, save the changes of the .bashrc file with source ~/.bashrc.
Now, run only the file name from anywhere in the home directory, and the script file will execute.
The result of the program should look something like this:
Conclusion
The Bash CLI is a tool every developer, regardless of expertise or experience, should use daily to make you productive and do fun things only with the terminal. Think of using Bash as a way to use your computer without the beautiful graphical user interface.
Top comments (0)