In continuation to our previous blog of Linux Bash Scripting for Beginners Part I where we went through the bash terminal and understanding how the command would be executed in the Linux shell. We also created our first bash script and we successfully executed to get the intended result. We will now go through the basic of bash such as Variables, Input & Output followed by some popular bash commands used frequently.
So let us quickly move to our topics without much delay.
Comments in Bash Scripting
Comments in bash scripting begin with a #. This indicates that the interpreter will disregard any line that starts with a # as a comment.
Adding comments to the code is a good practice because they aid in code documentation and make the code easier for others to understand.
Here are some instances of remarks:
# The interpreter will disregard both of these lines;
# this is an example comment.
Variables in Bash
Data can be stored using variables. Variables can be used throughout your script to read, access, and alter data.
In Bash, there are no data types. Variables in Bash can hold single characters, strings of characters, or numerical values.
The following are some methods that you can utilize and set the variable values in Bash:
Directly assign the value:
city=Bengaluru
Using command substitution, assign the value based on the output that a program or command produces. Keep in mind that in order to retrieve the value of an existing variable, $ is needed.
silicon_valley=$city
This assigns the value of city to the new variable silicon_valley
To access the variable value, append $
to the variable name.
admin@linux:~$ city=Bengaluru
admin@linux:~$ echo $country
Bengaluru
admin@linux:~$ new_city=$country
admin@linux:~$ echo $new_country
Bengaluru
Variables Naming Conventions
The following are the variable name conventions used in Bash scripting:
- Initial letters or underscores () are appropriate for variable names. Underscores (), numerals, and
- characters are all permitted in variable names.
- The case of variable names matters.
- Special characters or spaces should not appear in variable names.
- Make sure the variable’s names are clear and represent its intended use.
- Don’t name variables with reserved terms like if, then, else, fi, and so forth.
Let us see some example of Valid Variable name
_SAM
TOKEN_A
VAR_1
VAR_2
Examples of Invalid Variable name
3rdSAM (variable name starts with a number)
TOKEN NUM (variable name contains a space)
TOKEN-COUNT (variable name contains a hyphen)
Input & Output
Gathering Input
Let us start with discussing how can we provide inputs to our scripts
- Understanding how we will read the user input and store it in a variable
To answer that , we can read the user input using the read command
#!/bin/bash
echo "Today is " `date`
echo -e "\nenter the path to directory"
read the_path
echo -e "\nyour path has the following files and folders: "
ls $the_path
Output
[admin@linux ~]# bash find_path.sh
Today is Wed Dec 27 15:52:29 IST 2023
enter the path to directory
/tmp
your path has the following files and folders:
test_for_shell
2. This code reads each line from a file named input.txt
and prints it to the terminal. We’ll study while loops later in this article.
while read line
do
echo $line
done < input.txt
3. Command line Arguments
$1 indicates the first argument passed, $2 the second argument passed, and so on in a bash script or function.
This script publishes a customized greeting after receiving a name as a command-line option.
echo "Hello, $1!"
Let us supply “Linus” as the argument considering welcome.sh as the file name
#!/bin/bash
echo "Hello, $1!"
Output
[admin@linux ~]# bash welcome.sh Linux
Hello, Linux!
[admin@linux ~]#
Display the Output
Now we will discuss the ways how we can get the outputs from our scripts
- Print in the terminal
echo "Hello, World!"
The above will print “Hello, World!” to the terminal.
2. How to write to a file
echo "Example of Output Text." > output.txt
The above one writes the text “Example if Output Text” to a file named output.txt
. Please note that the >
operator overwrites a file if it already has some content.
3. Append to a file
echo "Adding Extra Lines" >> output.txt
This appends the text “Adding Extra Lines” to the end of the file output.txt
.
4. Redirecting the Output to a file
ls > files.txt
The result is written to a file called files.txt and contains a list of all the files in the current directory. This allows you to redirect any command’s output to a file.
Popular Bash Commands
Let me give you the quite popular bash commands which is commonly used in the scripting.
Command | Usage |
---|---|
ls | Lists the content of a directory |
alias | Define or display aliases |
unalias | Remove alias definitions |
pwd | Prints the working directory |
cd | Changes directory |
cp | Copies files and directories |
rm | Remove files and directories |
mv | Moves (renames) files and directories |
mkdir | Creates directories |
man | Displays manual page of other commands |
touch | Creates empty files |
chmod | Changes file permissions |
./ | Runs an executable |
exit | Exits the current shell session |
sudo | Executes commands as superuser |
shutdown | Shutdowns your machine |
htop | Displays processes and resources information |
unzip | Extracts compressed ZIP files |
apt , yum , pacman | Package managers |
echo | Displays lines of text |
cat | Prints file contents |
ps | Reports shell processes status |
kill | Terminates programs |
ping | Tests network connectivity |
vim | Efficient text editing |
history | Shows a list of previous commands |
passwd | Changes user password |
which | Returns the full binary path of a program |
shred | Overwrites a file to hide its contents |
less | Inspects files interactively |
tail | Displays last lines of a file |
head | Displays first lines of a file |
grep | Prints lines that match patterns |
whoami | Outputs username |
whatis | Shows single-line descriptions |
wc | Word count files |
uname | Displays OS information |
neofetch | Displays OS and hardware information |
find | Searches for files that follow a pattern |
wget | Retrieves files from the internet |
If you need to check more of such commands you can follow our Linux Cheat Sheet and Basic Linux Commands For Beginners
Conclusion
Finally we leant about the usage of comment in script files. How do we engage with variables was also learnt using the valid variables. Then we talked about the reading the inputs and displaying the outputs from our scripts file. At last we saw some basic bash commands which can be handy in our initial days of bash scripting. In our next part we will learn about the Conditional statements , looping & branching, scheduling the scripts using cron followed by troubleshooting & debugging skills.
Bash Project : GNU Project for Bash