Medium Linux Shellscript
Medium Linux Shellscript
Medium Linux Shellscript
Unix Architecture
LInux :
)Linux intro:
1
Most used linux distros currently
-RPM based: RHEL & Centos (paid version and downloaded .rpm)
-Debian based:ubuntu server & linux mint (free avaliable and downloaded .deb )
im — go to file
V
Default text editor in ubuntu is nano
)software management
4
1.Curl —--(predefined curl in linux and downloading and moving to file_name.rpm )
curl <link.rpm> -o file_name.rpm
—->(install ) rpm -ivh file_name.rpm
.yum install package and its dependencies for link or other like wget (like curl)--
2
apt command in ubuntu and yum in centos to manage packages
)Services
5
Systemctl —> systemctl status httpd
Systemctl start httpd
Systemctl restart httpd
Systemctl reload httpd
Systemctl enable httpd
Systemctl is-enabled httpd How to check if a service is enabled
String
cho $variable or ${variable} → to print the value
E
Echo ${#variable} → variable length
Echo ${variable:20} → print last 20 characters
Operators:
xpr 2 + 3
e
expr 2 \* 3
expr 10 / 2
expr 20 % 2
Ifelse conditions:
- gt → >
-ge → >=
-le → <
-ne → <=
-eq → ==
file.sh
If [ $a -gt $b ]
then
------
—
else
—----
fi
For loop:
for (( inst; condition; inc/dec ))
do
—---------
done
x:
E
for (( a=1; i<=10; i++ ))
do
echo $a
done → print 1 to 1o
Functions:
resk(){
g
echo “hello”
}
gresk —> calling function in shell script ****************fun call after writing only
File Management
. ls → list of directories
1
2. ls -l → list dir with file permissions and storage all details
1)Hidden Files
. ls -a → hidden files and folders
1
2)Creating Files
i file.txt
V
Shell script:
1. vi text.sh
!/bin/bash
#
echo “hello vi text.sh”
2. chmod 777 text.sh ----> give permision to text.sh
3. ./text.sh or bash text.sh or sh text.sh --->to run the vi file
Search:
1. / or ? To search
/chaitanya
?chaitanya ----->to search chaitanya (for next word n forword or N backword)
delete:
1. x ---> to delete from right one alpha
2. dw --> remove the word
3. dd ---> remove line
4. del ---->del button
Remove lines:
1. dG ---> curser(remove curser to end of file)
. d
2 lG ---->all above content remove above curser
3. : 10,15 d---> delete lines from 10 to 15
Move:
shift +g --->curser move to last of line
l+shift+g --->curser move to first of line
30+shift+g --->curser move to 30th of line
Screen Move:
shift +h --->curser move top of screen
shift + m ---->curser move middle of screen
shift +l ---->bottom of curser
Copy:
YY ---> copy
5YY --->copy 5 lines
p ---> paste
5)Copying Files
1. cp file.txt file.txt
6)Renaming Files
1. mv file.txt file.txt
7)Deleting Files
1. rm file1.txt file2.txt
8)File descriptions:
→ std i/p
0
1 → std o/p
2 → std error
Directory Management
cd
1. cd ~ or cd -----> directory to home
2. cd - -----> back dir
3. cd .. -----> one step back to dir
4. cd “chaita kiran” ---->to enter space dir
5. cd /home/chaitanya2/inside --->change path from home or cd inside --->change
also
1)Listing Directories
. ls dir
1
2. ls /dir1/dir2
2)Creating Directories
1. mkdir worker
4)Removing Directories
1. rmdir worker1 worker2
5)Renaming Directories
1. mv worker1 worker2
Search:
0.curl localhost:8080/80 --->to check content running on 80port
1. ls |grep -i kiran ---->search kiran in ls, -i --->case sensitive
ifconfig |grep -i inet addr ---> to show net address
2. only for files and folders
find chaitanya or locate chaitanya ----> to search files and fold
Processes Management
Listing Running Processes
. ps -f → show list all process
1
2. ps -ef |grep tomcat to check the tomcat running on which port
Stopping Processes
1. kill -9 6751(PID)
rocesses
p
–Top —-to see running processes
–Htop – to running process and ram status
–Ps -ef | grep httpd —-- to see the running services(all the process with their
parent process id) ps -aux — normal
–kill -9(force) PID command is to stop process forcefully
–kill PID is to stop process gracefully, child processes also will be stopped if
parent process is stopped gracefully.
telnet utility
1. Used to check the port open or not
EX: telnet 192.168.75.68: 8000
Shell scripting
---above regards shells
—
#!/bin/sh
Running ::
1. ./file.sh
2. sh file.sh
hell Types
S
In Unix, there are two major types of shells −
ourne shell− If you are using a Bourne-type shell,the $ character is the default
B
prompt.
C shell− If you are using a C-type shell, the % characteris the default prompt.
shell (csh)
C
TENEX/TOPS C shell (tcsh)
Variable Names
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or
the underscore character ( _)
EX :
_ALI
TOKEN_A
VAR_1
VAR_2
Not variable:
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
Special Variables
alues passing through the arguments
V
Sh file.sh arg1 arg2
$1 →1st argument
$2 →2nd argument or $11
$# →number arguments like 2
$$ →PID number 605670
$? → previous command execution status ******************************IMP
X:
E
#!/bin/sh
utput:
O
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
Shell Arrays
x:
E
#!/bin/sh
AME[0
N ]="Zara"
NAME[1 ]="Qadir"
NAME[2 ]="Mahnaz"
NAME[3 ]="Ayan"
NAME[4 ]="Daisy"
echo"First Index: ${NAME[0]}"
echo"First Method: ${NAME[*]}"
echo"Second Method: ${NAME[@]}"
utput :
O
$./test.sh
First Index: Zara
First Method: Zara Qadir Mahnaz Ayan Daisy
Second Method: Zara Qadir Mahnaz Ayan Daisy
Relational Operators
Assume variable a holds 10 and variable b holds 20
specific to numeric values. These operators do not work for string values
unless their value is numeric.
Boolean Operators
-o This is logical OR. If one of the operands is true, then [ $a -lt 20 -o $b -gt
the condition becomes true. 100 ] is true.
-a This is logical AND. If both the operands are true, then [ $a -lt 20 -a $b -gt
the condition becomes true otherwise false. 100 ] is false.
String Operators
Operator Description Example
= Checks if the value of two operands are equal or [ $a = $b ] is not true.
not; if yes, then the condition becomes true.
!= Checks if the value of two operands are equal or [ $a != $b ] is true.
not; if values are not equal then the condition
becomes true.
-z Checks if the given string operand size is zero; if it [ -z $a ] is not true.
is zero length, then it returns true.
-n Checks if the given string operand size is non-zero; [ -n $a ] is not false.
if it is nonzero length, then it returns true.
str Checks if str is not the empty string; if it is empty, [ $a ] is not false.
then it returns false.
#!/bin/sh
=0
a
while[$a-lt10]
do
echo $a
a=
̀ expr $a + 1`
done ##output ## 0,1,2,3,4,5,6,7,8,9
2) until loop →until loop executes until a givencondition becomes true.
#!/bin/sh
=0
a
until[!$a-lt10]
do
echo $a
a=
̀ expr $a + 1`
done ##output ## 0,1,2,3,4,5,6,7,8,9
)for loop
3
#!/bin/sh
forvarin0123456789
do
echo $var
done ############0,1,2,3,4,5,6,7,8,9
) select loop
4
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Loop Control
In this chapter, we will learn following two statements thatareusedtocontrolshell
loops−
#!/bin/sh
=0
a
while[$a-lt10]
do
echo $a
if[$a-eq5]
then
break
fi
a=
̀ expr $a + 1`
done ####### 01,2,3,4,5
#!/bin/sh
forvar1in123
do
forvar2in05
do
if[$var1-e
q2-a
$var2-e
q0]
then
break2
else
echo"$var1 $var2"
fi
done
done #####
Output:
1 0
1 5
#!/bin/sh
UMS="1 2 3 4 5 6 7"
N
forNUMin$NUMS
do
Q=̀ expr $NUM % 2`
if[$Q-eq0]
then
echo"Number is an even number!!"
continue
fi
echo"Found odd number"
done
utput:
O
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
CRONTAB:
!/bin/sh
#
NOW="$(date +'%d-%m-%Y')"
Note::: crontab
hmod +x /opt/script/delete-old-files.sh
c
crontab -e
0 7 * * * /bin/bash /opt/script/delete-old-folders.sh
MongoDB_Backup :
Backup.sh
Backup.sh
#!/bin/bash
Variables
#
CONTAINER_ID=`docker ps -q --filter="name=pg_postgres_postgres.1*"`
BACKUP_FOLDER=./backup/pg
TIMESTAMP=`date +%F-%H%M̀
cho 'Variables-------'
e
echo 'CONTAINER_ID='${CONTAINER_ID}
echo 'BACKUP_FOLDER='${BACKUP_FOLDER}
Clean up
#
echo 'Running cleanup-------'
rm -rf ${BACKUP_FOLDER}
mkdir -p ${BACKUP_FOLDER}
Backup commands
#
echo 'Generating backup-------'
for db in $(docker exec -i ${CONTAINER_ID} psql -U postgres -t -c 'SELECT dataname FROM
pg_database WHERE NOT datistemplate')
do
echo $db
docker exec -i ${CONTAINER_ID} pg_dump -U postgres --format=c ${db} >
${BACKUP_FOLDER}/${db}.sqlc
one
d
tar -zcvf $TIMESTAMP.tar.gz ./backup/pg
echo 'Done-------'
r
O
#send message to mailtrap box
STR=$(du -sh BACKUP_DIR)
echo "$TIMESTAMP DB backup size is $STR" | mail -s "DB daily backup alert"
d8e1a67424-278bbd@inbox.mailtrap.io
r m -rf /tmp2/backup/*
done
Note::: crontab
at 5 a.m every week with:
#
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
0 0 * * * bash /home/backup.sh