Bash Scripting Tutorial for Beginners – Part1

A script is command line program that contain a series of commands. Commands contain in a script executed by an interpreter. In case of shell script, the shell access the interpreter and executes the command listed in the script one after another.

An interpreter executes commands in the script. Anything you can type at the command line, you can put in a script. Scripts are good for automating tasks.

[[email protected] ~]# vim script.sh
#!/bin/bash
echo “Scripting is a fun…!!!”
[[email protected] ~]# chmod 755 script.sh
[[email protected] ~]# ./script.sh
Scripting is fun…!!!

#!/bin/bash can be spoken as shebang. If a script does not contain a shebang the commands are executed using your shell. Its best to explicitly specify the exact interpreter to be used.

Other shell examples:

#!/bin/csh
echo "This script uses csh as the interpreter"
#!/bin/ksh
echo "This script uses ksh as the interpreter
#!/bin/zsh
echo "This script uses zsh as the interpreter"

Variable in shell script:

Variable are simply the storage location that have a name, you can think variables as Name-Value pair.

Syntax:

VARIABLE_NAME="VALUE"

Not using the space before and after the equal sign. And also variable are case sensitive and by convention variables are uppercase.

Variable Usage:

To use a variable simply proceed variable name with $ sign. You can also enclose the variable name with curly braces and proceed the opening brace with $ sign. The curly brace syntax is optional unless you need to immediately proceed or follow the variable with additional data.

Here is an example:

#!/bin/bash
my_shell='bash'
echo "I am ${my_shell}ing on mykeyboard"

Output: I am bashing on my keyboard.

If you don’t encapsulate variable name in curly braces the shell will treat the additional text as a part of the variable name since the variable with that name doesn’t exist nothing is put at that place.

Assign command output to a variable:

#!/bin/bash
SERVER_NAME=${hostname}
echo "You are running this script on ${SERVER_NAME}."

Output: You are running this script on TechinicalMint.

In this example the output of hostname is stored in SERVER_NAME, in this case the hostname is TechnicalMint. You can also enclose the command in bactic “

Variable Name:

Valid name can contain Letters, Digits and Underscores. They can start with letters or underscores but not with digits.

Examples:

Valid Variables:

One2Three="ABC"
One_2_Three="ABC"
Onetwothree="ABC"

Invalid Variables:

3LETTERS="ABC"
One-two-three="ABC"
Onetwothree="ABC"

Test: check file types and compare values.

Syntax:

[ condition-to-test-for ]

Example:

[ -e /etc/passwd ]

This test checks whether or not the /etc/passwd file exists. If it does returns true i.e. command exits with status 0. If the file doesn’t exists, it returns false that means the command exits with status 1.

You can test all the conditions by running the command.

# help test
Common test you can perform.

-d FILE        True if file is a directory
-e FILE        True if file exists
-f FILE        True if file exists and is a regular file
-r FILE        True if file is readable by you
-s FILE        True if file exists and is not empty
-w FILE        True if the file is writable by you
-x FILE        True if the file is executable by you

You can read the man page by typing which will give you all the other test details and the examples.

# man test

 

Making Decision – The if Statement.

You know how to determine certain condition is true or not, you can now combine them with if statement to make decision in your script.

The if statement starts with the word if and is followed by a test. The following line contains the word then, next is command or a series of commands which will get executed if the tested condition returns true.

If [ condition-is-true ]
Then
   Command 1
   Command 2
   Command 3
fi

Finally the statement fi which is simply if spell backward.

Here is an example script.

#!/bin/bash
MY_SHELL="bash"
if  [ "$MY_SHELL" = "bash" ]
then
    echo "You seem to like bash shell"
fi

Output: You seem to like bash shell.

The best practice is to enclose the variables in quotes to prevent some unexpected side effects while performing conditional tests.

You can also perform an action if the condition is not true by using an if/else statement. Simply insert the else keyword and follow that by the command you want to execute if the condition is not true.

Syntax:

if [ condition-is-true ]
then
    Command N
else
   Command N
fi

Example:

#!/bin/bash
MY_SHELL=”csh”
if  [ “$MY_SHELL” = “bash” ]
then
     echo “You seem to like the bash shell”
else
     echo “You don’t seem to like the bash shell”
fi

Output: You don’t seem to like the bash shell

If/elif/else:

You can also test for multiple conditions using elif, the word elif is contraction for else if, like if follow elif with a condition to test for. The following line used the word then finally provide a series of command to execute if the condition for elif evaluates to be true.

if [ condition-is-true ]
then
Command N
elif [ condition-is-true ]
then
Command N
else
Command N
fi

Here is an updated version of the script using elif.

#!/bin/bash
MY_SHELL=”csh”
if [ “$MY_SHELL” = “bash” ]
then
    echo “You seem to like the bash shell”
elif [ “”MY_SHELL” = “csh” ]
then
    echo “You seem to like the csh shell”
else
    echo “You don’t seem to like the bash shell”
fi

Output:

You seem to like the csh shell.

for Loop:

If you want perform an action on a list of items, use a for loop. The first line of the “for” loop starts with the word for followed by variable name and then a list of items.

The next line contain the word “do”, places statement that you want to execute on the following line and finally end the for loop with the word “done” in a single line.

Syntax:

for VARIABLE_NAME in ITEM_1 ITEM_2 ITEM_N
do
command 1
command 2
command N
done

The first item in the list is assigned to the variable and code block is executed, next item in the list is then assigned to the variable and the command is executed. This happens to the each item in the list.

For example:

#!/bin/bash
for COLOR in red green blue
do
echo “COLOR: $COLOR”
done

Output:

COLOR: red

COLOR: green

COLOR: blue

We can see that there are 3 items in the list red, green and blue. The for loop executes 3 times the first time red is assigned to the variable COLOR and the echo COLOR command is run. The second time green is assigned to the variable COLOR. Third and final time blue is assigned to the variable COLOR and the echo command is executed. It’s a common practice for the list of items to be stored in a variable as in this example.

Another example:

#!/bin/bash
PICTURES=$(ls *jpg)
DATE=$(date +%F)
for PICTURE in $PICTURES
do
echo “Renaming ${PICTURE} to ${DATE}-${PICTURE} ”
mv ${PICTURE} ${DATE}-${PICTURE}
done

In this script, names all of the files ending .jpg are being renamed by inserting today’s date before the original filename.

$ ls
bear.jpg man.jpg rename-pics.sh
$ ./rename-pics.jpg
Renaming bear.jpg to 2018-12-08-bear.jpg
Renaming man.jpg to 2018-12-08-man.jpg
$ ls
2018-12-08-bear.jpg  2018-12-08-man.jpg  rename-pics.jpg

Positional Parameter:

Positional parameters are variable that contains the content of the command line, the variable from $0 to $9.

$ script.sh parameter1 parameter2 parameter3
$0:"script.sh"
$1:"parameter1"
$2:"parameter2"
$3:"parameter3"

The script itself stored in $0, the first parameter stored in $1, second in $2 and so on.

Here is an example:

$ vim archive_user.sh

#!/bin/bash
echo  “Executing script: $0”
echo  “Archiving user: $1”

# Lock the account
passwd –l $1

# Create an archive of the home directory.
tar cf /archieves/${1}.tar.gz /home/${1}

This script archive_user.sh accepts parameter which happens to be a user name. Anything that follows the # sign is a comment. The only exception to this is shebang on the first line. Comments are ignored by the interpreter, anything that follows the # sign is ignored.

Here is the output when we execute the script.

$ ./archive_user.sh technicalmint
Executing script: archive_user.sh
Archiving user: technicalmint
Locking password for user technicalmint
passwd: Success
tar: Removing leading `/' from member names

Another example:

$ vim archive_user.sh

#!/bin/bash
USER="$1"  # The first parameter is the user.
echo  "Executing script: $0"
echo  "Archiving user: $USER"
# Lock the account
passwd –l $USER
# Create an archive of the home directory.
tar cf /archieves/${USER}.tar.gz /home/${USER}

In this case it’ll assign it to the variable called USER, the output remain exactly the same.

Another example:

$ vim archive_user.sh

#!/bin/bash
echo "Executing script: $0"
for USER in [email protected]
do
echo "Archiving user: $USER"
# Lock the account
passwd –l $USER
# Create an archive of the home directory.
tar cf /archieves/${USER}.tar.gz /home/${USER}

You can access all the positional parameters starting at $1 to the very last one to the command line by using this special variable [email protected] sign.

Here is how to update the script to except one or more parameters, now you can pass multiple user to this script and the for loop will execute each user that you supplied on the command line.

# sh archive_user.sh technicalmint user1

Executing script: archive_user.sh
Archiving user: user1
Locking password for user user1.
passwd: Success
tar: Removing leading `/' from member names
Archiving user: technicalmint
Locking password for user technicalmint.
passwd: Success
tar: Removing leading `/' from member names

Accepting User Input (STDIN):

If you want to accept standard input, use the read command. A standard input typically comes from a person typing from keyboard but it can also come from other sources like the output of a command and command pipeline.

Syntax:

read –p “PROMPT” VARIABLE

Example:

#!/bin/bash
read –p "Enter a user name:  " USER
echo "Archiving user:  $USER"
# Lock the account
passwd –l $USER
# Create an archive of the home directory.
tar cf /archieves/${USER}.tar.gz /home/${USER}

# sh archive_read.sh
Enter a user name: technicalmint
Archiving user: technicalmint
Locking password for user technicalmint.
passwd: Success
tar: Removing leading `/' from member names

In this script I typed in user technicalmint.

 

That’s it in this article, hope you enjoyed it! Please share it across if you think it’s good. Comment below for your feedback or questions. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *