- Nikhil Bhaskar
- July 8, 2021
How to Create & Configure Shell Script file in Linux.
Shell Scripting is an open-source system program designed to be run by the Unix/Linux shell.It is a program to write a lines of commands for the shell to execute.
A shell script or sh-file is between a single command and a small program.We have multiples shell command & running multiple commands together.It is used for perform multiple tasks automatically.
Create a Shell Script.
vim scriptfile.sh
Write a simple code.
#!/bin/bash
# Print Example message
echo "Example!"
Provide execute permission.
chmod +x scriptfile.sh
Run the script file.
bash scritpfile.sh
or
./scriptfile.sh
Here is the command output.
root@ip-172-15-25-65:/home/ubuntu#bash scriptfile.sh
Example!
Syntax of Script file program
Only if Statement
- It is used to test single or multiple conditions.
if command
then
statement
fi
if-else Statement.
- It is used when we have 2 possible outcomes.
if command
then
statement1
else
statement2
fi
if-elif-else Statement.
- It is used when we have multiple conditions and different outcomes.
if condition1
then
statement1
elif condition2
then
statement2
else
statement3
fi
echo command:
- It is used to print the lines.
#!/bin/bash
echo "Print the message"
While Loop:
-
It is a control flow statement that executes a block of code at least once, and then repeatedly executes the code or not, depending on a given boolean condition at the end of the block.
#!/bin/bash
valid=true
count=1
while [ $valid ]
do
echo $count
if [ $count -eq 5 ];
then
break
fi
((count++))
done
For Loop:
-
It is a repetition control program that allows to efficiently write a loop that needs to execute a specific number of times.
#!/bin/bash
for (( counter=10; counter>0; counter-- ))
do
echo -n "$counter "
done
printf "\n"
User Input:
- It is is used to take input from user in bash.
echo "Enter Name"
read name
echo "$name"
Add,substract,multiply & divide the Numbers:
- We can add,substract,multiply & divide the number is bash program.
Add Two numbers.
#!/bin/bash
echo "Enter first number"
read x
echo "Enter second number"
read y
(( sum=x+y ))
echo "The result of addition=$sum"
- We can create a folder/directory using bash file.
#!/bin/bash
echo "Enter directory name"
read newdir
`mkdir $newdir`
- We can read any file line by line in bash by using loop.
#!/bin/bash
file='book.txt'
while read line; do
echo $line
done < $file
#!/bin/bash
echo "Enter file-name to delete"
read fn
rm -i $fn
- Using bash, we can send a mail.
#!/bin/bash
Recipient=”[email protected]”
Subject=”Topic”
Message=”Welcome”
`mail -s $Subject $Recipient <<< $Message`