What is Shell?
Shell allows a user to interact with kernel and provide an environment to execute commands.
Types of Shell
- bash
- sh
- ksh
- tsh
- fish
- zsh
How to check your default shell?
poyadav@fedora:~$ echo $0bash
What is shell scripting?
We can use shell scripting to automate tasks, it contains a set of commands to perform a task which are executed sequencially.
What is shebang?
#!/bin/bash
It tell our system to use bash for executing the script.
How to execute as bash script?
- ./file.sh #Make sure file has execute command (chmod +x file.sh)
- /path/file.sh #Make sure file has execute command
- bash file.sh
Variables
var=hello
var=$(command)
readonly var=value
Arrays
myarray=(1 2 3 "hello" "hii") #contains space seperated values
echo "${myarray[2]} #getting 3rd value
echo "${myarray[*]} #gatiing all values
echo "${myarray[*]:2} #getting specific values
array+=(bye tata) #adding new values
Key-Value arrays
declare -A myarray
myarray=( [name]=Henry [age]=23 )
echo "${myarray[name]}"
Strings Operations
myvar="Hello, how are you?"
length=${#myvar}
upper=${myvar^^}
lower=${myvar,,}
replace=${myvar/Hello/Hey}
slice=${myvar:2:5}
Getting input from user
echo -n "What is your name? "
read name
echo "Your name is $name"
read -p "What is your age? " age
echo "Your age is $age"
Arithmetic Operations
let a++
let a=6*10
((a++))
((a=6*10))
if-else
if [ condition ];then
echo "PASS"
else
echo "FAIL"
fi
case
echo "where you want to go"
echo "a=Paris"
echo "b=London"
echo "c=USA"
read choice
case $choice in
a) echo "Going to Paris";;
b) echo "Going to London";;
c) echo "Going to USA";;
*) echo "Not going anywhere"
esac
Logical Operators
#Both conditions need to be true/met
if [[ condition1 ]] && [[ condition2 ]];then
echo "PASS"
else
echo "FAIL"
fi
if [[ condition1 ]] || [[ condition2 ]];then
echo "PASS"
else
echo "FAIL"
for Loop
for i in 1 2 3 4 5
do
echo i
done
#or we can also use
for i in Apple banana grapes
for i in {1..10}
#for loop with file
file=array.sh
for i in $(cat $file);do
echo $i
done
#or we can also use
for ((i=0;i<10;i++))
do
echo "Hello $i"
done
while Loop
#syntaX
count=0
num=10
while [ $count -lt $num ];do
echo "value is $count"
(( count++ ))
done
#reading from file
while read myvar;do
echo $myvar
done < myfile
#while with csv file
while IFS="," read id name age
do
echo "id is $id"
echo "name i $name"
echo "age is $age"
done < file.csv
Infinite Loop
while true;do
echo "Hey"
done
#for infinite loop
for (( ;; ));do
echo "Hey'
done
Functions
fun() {
echo "hello"
}
#another way
function myfun {
echo "Hey"
}
#function with args
myarg() {
echo "Hello $1"
echo "Welcome to $2"
}
fun
myfun
myarg raju manali
No comments:
Post a Comment