0% found this document useful (0 votes)
20 views

Linux - Shell Scripting

Uploaded by

harsh.testing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Linux - Shell Scripting

Uploaded by

harsh.testing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Topic Desciption Command Remark

How to check in which shell you are / echo $0


How to see all the available shells cat /etc/shells
SHELL BASICS
Another way to check your shell is cat /etc/passwd
How to start your bash file? #!/bin/bash
How to define and store variable var_name=value
Variables
How to store the linux command in a variable? var_name=$(hostname)
How to use defined variable in use? echo $var_name
How to use defined variable in use with string? echo my name is $name
echo "my name is ${name} and age is ${agevar}"
How to get result of a command witin a string echo "my hostname is $(hostname)" will print hostname

Echo #!/bin/bash

#To display the user typed in terminal


How to display the last typed command in terminal echo "User typed: ${0}"

Output: When user run this script using . /script_name


o/p will be: User typed: ./script_name (which will be last typed )
cat << EOF
.....
How to Write multiple lines lines
.....
EOF

If you print these

x=Hello echo $xLength


To perform some operations on strings y="New World" echo $xUpper
echo $xLower
Like finding strength of a string xLength=${#x} echo $newString
String Operations convert the string into Upper or Lower Case xUpper=${x^^}
xLower=${y,,} Output
replace a string with something else Hello
cut a portion of string newString=${y/World/Life} 5
sliceString=${y:start_position:length} HELLO
new world
New Life

read var_name_to_store_value

or
If in a same line you want to
User Interaction How to take input from user display a text and get the user
read -p "Your name" var_name_to_store_value
input
To store the values in an array from a user
read -a myarray. (user need to provide space separated values)

{ls; pwd; hostname}


Block of Code If we need to execute multiple commands, we can use block of code
condition1 && {ls; pwd; hostname}

myArray=( 1 2 Hello "Hey Buddy")

echo "${myArray[0/1/2]}"

To get length of an array


"${#myArray[*]}"
We can define multipel values in array values are space separated
"${myArray[*]:1}" from index 1 to all values
"${myArray[*]:1:2}" 2 values from index 1
Arrays
To update an array with new values
myArray+=( 5 6 8 )

declare -A myArray

Array with key-value pairs myArray=( [name]=Prashant [age]=28 )


myArray[name]=Prashant

test 8>5 (1 means true, 0 means false) recommed to use double [[]]
which is the enhanced version
TEST Condition How to check the conditions [ 8 -eq 5 ] ( <,> are not working in single [])
of single [] and provide more
[[ 8 -eq 5 ]]
functionalities

if [ $age -eq 18 ]
then
echo "You are eligible to vote"
How to write if-else condition Keep the spacing in mind
else
echo "Sorry you are not eligible to vote"
fi
-eq / ==
-ge
-le
What are the different conditional opertaions we can use with if-else
-ne / !=
-gt
-lt

IF-ELSE
Topic Desciption Command Remark

if [ -d folder_name] If folder exists


if [ ! -d folder_name] If folder not exists

IF-ELSE if [ -f file_name] If file exists


if [ ! -f file_name] If file not exists
If you wanna check the existence of file or folder using IF condition
if [ -z $str ] If string is empty
if [ -e /path ] If path exists for not

if [ -r/w/x /file_path ] If path is readable/writable/executable or not

if [ $country = "India" ]
then
echo "You are Indian"
elif [ $country = "Nepal" ]
For multiple If-Else condition then
echo "You are from Nepal"
else
echo "You are from Earth"
fi
for i in 1 2 3 4 5
do
How to write a for loop echo Number is $i
done

for j in eat poop sleep

for p in {1..20}
Different options to write for loop

FOR LOOP for ((i=0;i<=10;i++))

To iterate through all the argument passed while running script for i in $@
Infinite loop using foor for ((;;))
hosts="/home/pparadkar/scripts/items"

for item in $(cat $items)


How to iterate the values from a file
do
echo $item
done
count=0
num=10

while [ $count -le $num ]


How to write a while loop
do
echo Numbers are $count
let count++
done
while read myvar
do
WHILE LOOP While loop to get the line by line content from a file
echo $myvar
done < file_path

while read IFS="," f1 f2 f3 f4 f5 IFS is internal field separator


do
While loop to get the values from file which are not separated by space? echo $f2 space is default so in case
echo $f3 values are separated by space
done < file_path so no need to specify IFS

Getting the values from csv file (as first row is column name) cat filename | awk '!NR=1 {print}' | while IFS="," read f1 f2 f3
a=0

until [ ! $a -lt 10 ]
UNTIL LOOP How to write until loop do
echo $a
a=`expr $a + 1`
done
using let command
let a++
let a=5*10

we can use
EXPRESSIONS How to perform airthmetic operation in script (( sum=x+y )) or echo "(( x+y ))"

To perform the decimal operations like


bc<<<"$x+$y"
bc<<<"scale=2;$x/$y"
Topic Desciption Command Remark
#!/bin/bash

echo Welcome to the CASE study


echo
* is anything else expect the
echo Hey choose an option given pattern in cases
echo
echo a = To see the current date it's like default in the switch-
echo b = list all the files in current dir case
echo c = TO see all the users logged in
------------------------------------------
echo d = TO check the system uptime
CASES How to write a cases-switch ----------
read choice If want to use the multiple
parameters in same case
case $choice in then we can use | sign
a) date;;
b)ls;; ex: a) param1 | param2 |
c)who;; param3 ;;
d)uptime;;
*) echo "Non a valid input"
esac

Connection Check How to check the connectivity with the remote server ping hostname
#!/bin/bash
host="192.168.29.21"
host1="www.google.com"

hosts="/home/pparadkar/scripts/hosts"
The $? variable represents the
exit status of the previous
for ip in $(cat $hosts)
command. ... As a rule, most
How to check the connectivity with the remote server for multiple hosts defined in a do
Connection Check commands return an exit status
separate file named hosts ping -c1 $ip &> /dev/null
of 0 if they were successful,
if [ $? -eq 0 ] and 1 if they were
then unsuccessful.
echo OK
else
echo NOT OK
fi
done
It make our life easy by
How to create an alias for a command alias d="ls -ltr | awk '{print \$9}'" creating a shortcut of the most
Alias used commands
How to create alias for a specific user echo alias hh="hostname" >> /home/<user>/.bashrc
How to create alias for all the user globally echo alias hh="hostname" >> /etc/bashrc
How to get the no. of arguments passed to a script echo "you have passed ${#} arguments"
How to display the argument passed with script echo $@
ARGUMENTS
How to display a specific argument, ex arg1, arg2, arg3
echo $1
I want to print arg1
sleep 1s
SLEEP We can use sleep command to create a delay between two task
sleep 1m
NULL DEVICE If you dont wanna print the output of a command in script hostname > /dev/null it is called as null device
now this varaible is constant
READONLY If you want to make any gloabal variable inside a script as constant readonly var_name = 123
and con't be change
Could be useful if out of
Suppose we have three argument 1-A, 2-B, 3-C multiple arguments, we need
if we just use shift command in our script so arguents will shift like below first argument and then
shift shift
remaining all togther
then 1-B, 2-C
1-A and (2-B 3-C)
To generate a random no.
you can find its detail under
RANDOM can be used to generate random passwords etc echo $RANDOM
man bash
NOTE: It is a bash variable
There are two ways
---------------------------------

function myfun {}

myfun() {
local var = "hello" local variable is only accessible
In order to avoid the repetative code in the script, you can use the function
} inside the function

---------------------------------
Functions
To call the function, just use the name of the function like
myfun

myfun() {
local num1 = $1
local num2 = $2
How to use the arguments/parameters in function sum = num1 + num2
}

myfun 12 13
LOGGER If you want to log your content or messages of script into /var/log/messages file logger "hello"
Topic Desciption Command Remark

while getopts vl:s OPTION


do
case ${OPTION} in
v)
VERBOSE='true'
Use to parse optional paramters from command line log 'Verbose mode on.'
getopts optstring name [args] ;;
l)
optsting contains the option characters to be recognized LENGTH="${OPTARG}"
GETOPTS
;;
If character is followed by colon : then it will be expecting an argument separated s)
by white space USE_SPECIAL_CHARACTER='true'
When there is an argment passed, it will be stored in OPTARG variable ;;
?)
usage
;;
esac
done

NUM$(( 1+2 ))

DICEA='3'
DICEB='6'
Ways to perform mathematic operations TOTAL=$(( DICEA + DICEB ))

(( NUM++ ))

INFINITE LOOP How to make an infinite loop? while true

We can use the below conditions with double [[]]


condition1 && condtion2
condition1 || condtion2
!condtion (opposite of result)

LOGICAL OPERATORS How to use logical operators !, &&, || With single [], we can only use the below
condition1 -a condition2
condition1 -o condition2

[[ $x=yes && $y=y ]]


[[ $x=~y|yes ]]

condition1 && condition2 || condition3


Ternary Operator
If 1 is true then execute2
else execute 3
realpath: convert each filename argument to an absolute pathname but it
don't validate path
realpath
basename string operations on path basename: strip directory info, strips suffixes from filename
dirname
dirname: if you provide the path with filename, it remove the filename and
provide the directory path

set -x (print command before executing it in script)


set -n (syntax check)
set -e (exit script if any command fails)
Debugging Properties
to enable the debugging we can set some properties in the beginning of script
while executing also you can provide these
bash -x script.sh
bash -e script.sh

REMOTE ACCESS Different options to write for loop ssh -t -o StrictKeyHostChecking=No user@<hostname> "date;hostname"

sshpass -p "<password>" ssh -t -o StrictKeyHostChecking=No


user@<hostname> "date;hostname"

or set SSHPASS variable


SSHPASS="<pass>"
We can provide the password while doing remote operations
sshpass -e ssh -t -o StrictKeyHostChecking=No user@<hostname> "date;
hostname"

or from file
sshpass -f <file_path>

You might also like