Variables in Shell Scripting
The variable is a location or placeholder for storing data. The value of the variable can be changed during the program execution The value assigned could be a number, text, filename, device, or any other type of data. A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables
Variable names
▪ Must start with a letter or underscore
▪ Do not use special characters such as @,#,%,$
▪ Allowed: VARIABLE, VAR1234able, var_name, VAR
▪ Not allowed: 1var, %name, $myvar, var@NAME, myvar-1
▪ Case sensitive
▪ To reference a variable, prepend $ to the name of the variable ▪ Example: $PATH, $LDLIBRARY_PATH, $myvar, etc.
Types of variables
1. Local Variable 2. Global Variable
1. Local Variable
▪ Only visible to the current shell
▪ Not inherited by subshells
Created and maintained by the user. This type of variable defined may use any valid variable name, but it is good practice to avoid all uppercase names as many are used by the shell.
2. Global Variable / System Variable
▪Inherited by subshells (child process, see next slide)
▪ provide a simple way to share configuration settings between multiple applications and processes in Linux
▪ Using all uppercase letters by convention o Example: PATH, LD_LIBRARY_PATH, DISPLAY, etc.
▪ printenv / env lists the current environmental variables in your system.
Created and maintained by the Linux bash shell itself. This type of variable is defined in CAPITAL LETTERS. There are many shell-inbuilt variables that are used for administration and writing shell scripts. To see all system variables, type the following command at a console/terminal: env or printenv
Quotations in Shell Script
Single quotation: Enclosing characters in single quotes (' ') preserves the value of each character within the quotes.
[alex@host ~]$ str1='echo $USER'
[alex@host ~]$ echo "$str1"
Output - echo $USER
Double quotation: Enclosing characters in double quotes (" ") removed the meaning of those characters (except \ and $).
[alex@host ~]$ str2="echo $USER"
[alex@host ~]$ echo "$str2"
Output - echo alex - will substitue the $USER with username
Back Quote: Command substitution (``) allows to execute command
[alex@host ~]$ str3=`echo $USER`
[alex@host ~]$ echo "$str3"
Output - alex
Note: Always use double quotes around variable substitutions and command substitutions: "$foo", "${foo}"
Special Characters:
# - Start a comment line
$ - Indicate the name of a variable
</mark> - Escape character
{} - Enclose name of variable
; - Command separator. Permits putting two or more commands on the same line.
;; - Terminator in a case option.
. "dot" command, equivalent to the source (for bash only)
| - Pipe: use the output of a command as the input of another one
> < - Redirections (0<: standard input; 1>: standard out; 2>: standard error)
[ ] - Test expression, eg. if condition
[[ ]] - Extended test expression, more flexible than [ ]
||, &&, ! - Logical OR, AND and NOT
$0 - The filename of the current script.
$# - The number of arguments supplied to a script.
$ - All the arguments are double-quoted. If a script receives two arguments, $ is equivalent to $1 $2.
$@ - All the arguments are individually double-quoted. If a script receives two arguments, $@ is equivalent to $1 $2.
$? - The exit status of the last command executed.
$$ - The process number of the current shell. For shell scripts, this is the process ID under which they are executing.
$! - The process number of the last background command.
Escape character
When using echo -e, you can use the following special characters.
-e here enables the interpretation of backslash escapes
\b backspace - it removes all the spaces in between the text
\c suppress trailing newline
\n new line
\t horizontal tab
\v vertical tab
\r carriage return
\a alert (BEL)
echo -n option suppresses newline
Example: escape_characters.sh
echo -e "Hello \bWolrd"
echo -e "Hello \cWorld"
echo -e "Hello \nWorld"
echo -e "Hello \tWorld"
echo -e "Hello \vWorld"
echo -e "Hello \rWorld"
echo -e "Hello \aWorld"
Shell Function
A function is a collection of statements that execute a specified task
A function is used to perform repetitive tasks.
A bash function is a method used in shell scripts to group reusable code block
Shell Features
Assist with code reuse
Enhance the program’s readability
Allow for easy maintenance
Syntax:
To declare a function, simply use the following syntax −
function_name () {
list of commands
}
The name of your function is function_name, and that's what you will use
to call it from elsewhere in your scripts. The function name must be
followed by parentheses, followed by a list of commands enclosed within
braces.
eg.
#!/bin/bash
# Define your function here
Hello () {
echo "Hello World"
}
# Invoke your function
Hello
In the ever-evolving landscape of DevOps and automation. scripting has become an indispensable tool for streamlining tasks, boosting productivity, and ensuring consistency.
Today let's cover the advance of shell scripting with some hands-on practicals.
Shell Scripting Examples
Task 1: Write a bash script when the script is executed with three given arguments (one is the directory name, the second is the start number of directories and the third is the end number of directories ) it creates a specified number of directories with a dynamic directory name.
#!/bin/bash
dname=$1
start_num=$2
end_num=$3
for (( i=$start_num; i<=$end_num; i++ ))
do
mkdir "$dname$i"
done
echo "All Directories created successfully!"
You can save this script in a file named createDirectories.sh and then execute it from the terminal using the command ./createDirectories.sh <directory-name> <start-number> <end-number>.
For example, to create 90 directories with names day1 to day90, you can execute the following command:
./createDirectories.sh day 1 90
Task 2: Write a Shell Script to back up all your work.
Backup script
#!/bin/bash
src_dir=/home/ubuntu/scritps
tgt_dir=/home/ubuntu/backup
current_timestamp=$(date "+%Y-%m-%d-%H-%M-%S") or $(date "+%d-%m-%y")
echo $current_timestamp
final_file=$tgt_dir/script-backup-$current_timestamp.tgz
tar -zcvf $final_file -C $src_dir .
if [ $? -eq 0 ]
then
echo "Backup Complete"
else
exit 1
fi
The Same backup script in function
#!/bin/bash
create_backup {
src_dir=/home/ubuntu/scritps
tgt_dir=/home/ubuntu/backup
current_timestamp=$(date "+%Y-%m-%d-%H-%M-%S") or $(date "+%d-%m-%y")
echo $current_timestamp
final_file=$tgt_dir/script-backup-$current_timestamp.tgz
tar -zcvf $final_file -C $src_dir .
echo "backup completed"
}
echo "starting backup process....................."
# calling function create_backup
create_backup
echo "Backup Completed ....................."
Task 3: Read About Cron and Crontab, to automate the backup Script
What is cron?cron
is a time-based scheduling utility in Linux. It allows you to automate repetitive tasks by running commands or scripts at specified intervals.
What is crontab?crontab
is a file that contains a list of commands or scripts scheduled to run automatically
Commands
crontab -l - > to show all the current jobs
crontab -e -> to edit or add new jobs
Cronjob Format
*/5 * * * * /bin/bash /home/ubuntu/backup_script.sh
Task 4: Read about User Management and Create 2 users using shell script and just display their Usernames.
What is User management?
User management is the process of controlling and managing the user accounts and their access rights to various resources in a computer system. This involves creating, modifying, and deleting user accounts, as well as assigning or revoking privileges or permissions for users.
User accounts are used to access a Linux system, and user management involves creating, modifying, and deleting these accounts.
User accounts are associated with a username, password, and unique user ID (UID).
User accounts can be assigned to one or more groups, which determine the user's access to system resources.
User management includes setting permissions for files and directories to control user access to them.
User management is essential for system security, as it allows administrators to restrict access to sensitive information and prevent unauthorized actions by users.
Create 2 users using shell script and just display their Usernames
#/bin/bash
user1=$1
user2=$2
#Creating Users
echo "Adding Users $user1 and $user2"
sudo useradd $user1
sudo useradd $user2
if [ $? -eq 0 ]
then
echo "Users added successfully"
else
exit 1
fi
Thank you for reading. I hope you will find this article helpful. if you like it please share it with others
Mohd Ishtikhar Khan : )