Linux Bash Scripting for Beginners – Shell Script and Command Line Part II

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

  1. 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

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

Display the Output

Now we will discuss the ways how we can get the outputs from our scripts

  1. 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.

CommandUsage
lsLists the content of a directory
aliasDefine or display aliases
unaliasRemove alias definitions
pwdPrints the working directory
cdChanges directory
cpCopies files and directories
rmRemove files and directories
mvMoves (renames) files and directories
mkdirCreates directories
manDisplays manual page of other commands
touchCreates empty files
chmodChanges file permissions
./Runs an executable
exitExits the current shell session
sudoExecutes commands as superuser
shutdownShutdowns your machine
htopDisplays processes and resources information
unzipExtracts compressed ZIP files
aptyumpacmanPackage managers
echoDisplays lines of text
catPrints file contents
psReports shell processes status
killTerminates programs
pingTests network connectivity
vimEfficient text editing
historyShows a list of previous commands
passwdChanges user password
whichReturns the full binary path of a program
shredOverwrites a file to hide its contents
lessInspects files interactively
tailDisplays last lines of a file
headDisplays first lines of a file
grepPrints lines that match patterns
whoamiOutputs username
whatisShows single-line descriptions
wcWord count files
unameDisplays OS information
neofetchDisplays OS and hardware information
findSearches for files that follow a pattern
wgetRetrieves 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

Leave a comment