Reading user input with timeout:

read -t

eg.

echo -n “Are you Sure ? ”

if read -t 5 response; then

echo ” Timed out, you didn’t make a selection”

else

echo “Ok proceeding”

fi

** Read with prompt :**

read -p “Enter Name: ” name

Get File Name from full path:

filename=$(basename $fullfile)

To Get the Extension:

extension=${filename##*.}

Filename without extension:

filename=${filename%.*}

Get Unix Timestamp:

stamp=date +%s

Unix Timestamp to Date :

date -d @

Testing If a file exists:

if [ -f testfile ]
then
echo testfile exists!
fi

[ d = directory  , s = file is not zero size , b = block device, c = character device, h = symbolic link, L = symlink, r = has read permission, w = has write permission, x = has execute permission, g,u,k = sgid, suid and sticky bit set , O = runner is owner, G= gid same as runner, N = modified since last run, f1 -nt f2  => f1 newer than f2 , f1 -ot f2=> older]

For Loop:

for i in seq 1 10;

do

echo $i

done

While Loop:

COUNTER=0
while [  $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done

Until Loop:

COUNTER=20
until [  $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done

If else :

T1=”foo”
T2=”bar”
if [ “$T1” = “$T2” ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi

Creating Menu with select:

OPTIONS=”Hello Quit”
select opt in $OPTIONS; do
if [ “$opt” = “Quit” ]; then
echo done
exit
elif [ “$opt” = “Hello” ]; then
echo Hello World
else
clear
echo bad option
fi
done

Checking Usage (Arguments ) :

if [ -z “$1” ]; then
echo usage: $0 directory
exit
fi

Getting Return Value :

Return value is obtained by special variable : $?

Capture command output into a variable :

DBS=mysql -uroot  -e”show databases”
for b in $DBS ;
do
mysql -uroot -e”show tables from $b”
done

String Comparision:

s1 = s2 => s1 matches s2

s1 != s2 => s1 does not match s2

-n s1 => s1 is not null (contains one or more characters)

-z s1 => s1 is null

Arithmetic Operators :

-lt (<)

-gt (>)

-le (<=)

-ge (>=)

-eq (==)

-ne (!=)

Check if last command Executed Successfully:

if [ $? -eq 0 ]; then 
 echo "Done"; 
else 
 echo "Didn't Work"; 
fi```