Thursday, May 31, 2018

Gracefully Exit Firefox using shell script and xdotool,Linux Teacher Sourav,Kolkata 09748184075

sudo apt-get install xdotool

if [[ -n `pidof firefox` ]];then
  WID=`xdotool search "Mozilla Firefox" | head -1`
  xdotool windowactivate --sync $WID
  xdotool key --clearmodifiers ctrl+q
fi



Source:http://how-to.wikia.com/wiki/How_to_gracefully_kill_(close)_programs_and_processes_via_command_line

Sending notifications alert to the User if battery status getting less than a threshold and shutdown the pc using shell script,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/bash
#01/06/2018


while true
do
    battery_level=`acpi -b | acpi -b | cut -f4 -d ' '|tr -d ',%'`
    if [ $battery_level -le 5 ]; then
       notify-send "Battery is less than 5%!" "Charging: ${battery_level}%" " Please connect the charger ,the system will shutdown after 2 minute"
shutdown -P +2 "Shutdown script started"
  
    elif [ $battery_level -le 20 ]; then
       notify-send "Battery is lower than 20%!" "Please connect the charger: ${battery_level}%"
      

 

    fi

    sleep 10 # run this script in every 10 seconds
done


Source:https://askubuntu.com/questions/518928/how-to-write-a-script-to-listen-to-battery-status-and-alert-me-when-its-above?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Saturday, May 26, 2018

Shell script to play Constant sound until user press a button when a new user logs on,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 27/05/2018
#
export BEEP=/usr/share/sounds/ubuntu/ringtones/Harmonics.ogg
alias beep='paplay $BEEP'
beepsound()
{
while [ 1 ]
do
beep
 read -t 0.25 -N 1 input
    if [[ $input = "q" ]] || [[ $input = "Q" ]]; then
# The following line is for the prompt to appear on a new line.
        echo
        exit

    fi
done
}

echo "New User Login Alert,Press Q to stop the beep"
numusers=`who | wc -l`
while [ true ]
do
currusers=`who | wc -l`
# get current number of users
if [ $currusers -gt $numusers ] ; then
echo "Someone new has logged on!!!!!!!!!!!"
date
who

beepsound
numusers=$currusers
elif [ $currusers -lt $numusers ] ; then
echo "Someone logged off."
date
numusers=$currusers
fi
sleep 1 # sleep 1 second
done



Friday, May 25, 2018

Do a task if your partition usage is greater than a given percentage using shell script,Linux Teacher Sourav,Kolkata 09748184075

a=$(df -h | grep -E 'root' | awk ' { print $5 " " $1}' | cut -f1 -d " " )
echo $a

b=${a::-1}
echo $b
if [ $b -ge 90 ] ; then
echo "hello"
else
echo "nope"
fi


in terminal you do it like this

df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | awk '{ print $1}' | cut -d '%' -f1 

Check a string if it is palindrome in shell script using rev command and without the use of rev command,Linux Teacher Sourav,Kolkata 09748184075

#/bin/sh
#25/05/2018

#in our class there is a very common task to see a string is palindrome or not

#for example aba is a string that will be same when altered from the opposite direction

#another example is 1991
#do you understand the assignment
#yes

#so let us ask the user to give us a string

echo "Please enter a string to be checked whether it is a palindrom"

read answer

echo "the string you entered is stored in the answer variable and it is $answer"

#there is an utility called rev by which we can do it just by a command

reverse=`echo $answer | rev`
#echo $reverse
#if [ $answer == $reverse ] ; then

#echo "the entered string is palindrome"

#else

#echo "the entered string is not palindrome"

#fi


#so it's working,however if we like we can do it without the use of rev command

#this backtick is used for evaluation ,like whatever inside the backtick will be evaluated

#and then be assigned to the left side

#wso to perform the same task without using rev

#we need to find the length of the string(for example the length of hello is 5

lenofword=$(echo -n $answer | wc -m)

echo the length of the word is $lenofword


#i am using shell command wc -m to get the character count,what could the problem
#for character we use -c, right?


#yes my mistake
#for some reason it's not working right now ,let me search a solution and will get back to you
#ok. leave it here. now can we work on the script i shared.


#yes sure

#i will come back to this later
#sometimes in shell script i forget the syntax,will check surely
reverse=""
for(( i=lenofword;i>=0;i--)) ; do
reverse+=${answer:i:1}



done

#echo $reverse

if [ $answer == $reverse ] ; then

echo "the entered string is palindrome"

else

echo "the entered string is not palindrome"

fi

Wednesday, May 23, 2018

Trap in shell script,invoking subroutine using a key combination,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 23/05/2018
#
echo "Usage of trap in Shell Script,for example a key combination can invoke a subroutine"
trap catchCtrlC INT
# Initialize the trap
# Subroutines
catchCtrlC()
{
echo "Entering catchCtrlC routine."
}
# Code starts here
echo "Press Ctrl-C to trigger the trap, 'Q' to exit."
loop=0
while [ $loop -eq 0 ]
do
read -t 1 -n 1 str
rc=$?
if [ $rc -gt 128 ] ; then
echo "Timeout exceeded."
fi
if [[ "$str" = "q" || "$str" = "Q" ]] ; then
echo "Exiting the script."
# wait 1 sec for input or for 1 char
loop=1
fi
done
exit 0

Tuesday, May 22, 2018

Make your Shell Script interactive using read command,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 23/05/2018
#
echo "Usage Of Read Command in Linux"
rc=0 # return code
while [ $rc -eq 0 ]
do
read -p "Enter value or q to quit: " var
echo "var: $var"
if [ "$var" = "q" ] ; then
rc=1
fi
done
rc=0 # return code
while [ $rc -eq 0 ]
do
read -p "Password: " -s var
echo ""
# carriage return
echo "var: $var"
if [ "$var" = "q" ] ; then
rc=1
fi
done
echo "Press some keys and q to quit."
rc=0
# return code
while [ $rc -eq 0 ]
do
read -n 1 -s var # wait for 1 char, does not output it
echo $var # output it here
if [ "$var" = "q" ] ; then
rc=1
fi
done
exit $rc

Monday, May 21, 2018

Automatic backing up a file if any changes occur in a regular interval,Linux Teacher Sourav,Kolkata 09748184075



 sh ./autobackup.sh a1.txt usb/ 3

 autobackup.sh=script name

a1.txt=file to be monitored

3=interval of checking in seconds

 autobackup.sh

#!/bin/sh
#
# automatically creating a backup of a file if the any changes to the file occurs
# the script that automatically backs up everytime with an incremented number is needed
# Checks that /back exists
# Copies to specific USB directory# Checks if filename.bak exists on startup, copy if it doesn't
# 22/05/2018
if [ $# -ne 3 ] ; then
echo "Usage: autobackup filename USB-backup-dir delay"
exit 255
fi
# Create back directory if it does not exist
if [ ! -d back ] ; then
mkdir back
fi
FN=$1 # filename to monitor
USBdir=$2 # USB directory to copy to
DELAY=$3 # how often to check
if [ ! -f $FN ] ; then # if no filename abort
echo "File: $FN does not exist."
exit 5
fi
if [ ! -f $FN.bak ] ; then
cp $FN $FN.bak
fi
filechanged=0
while [ 1 ]
do
cmp $FN $FN.bak
rc=$?
if [ $rc -ne 0 ] ; then
cp $FN back
cp $FN $USBdir
cd back
sh ./createnumberedbackup.sh $FN
cd ..
cp $FN $FN.bak
filechanged=1
fi
sleep $DELAY
done
****************************************************
createnumberedbackup.sh


#!/bin/sh
#let me show you this script which is able to back up of files in the same directory and number
#the backup,in devops it is very common the save the project with revision number,this
#script is not that complex though


echo "Create Numbered Backup from files of the current directory given as argument"
if [ $# -eq 0 ] ; then
echo "Usage: sh ./createnumberedbackup.sh filename(s) "
echo " Will make a numbered backup of the files(s) given."
echo " Files must be in the current directory."
exit 255
fi
rc=0 # return code, default is no error
for fn in $*  # for each filename given as arguments

do
if [ ! -f $fn ] ; then # if not found
echo "File $fn not found."
rc=1 # one or more files were not found
else
cnt=1 # file counter
loop1=0 # loop flag
while [ $loop1 -eq 0 ]
do
tmp=bak-$cnt.$fn
if [ ! -f $tmp ] ; then
cp $fn $tmp
echo "File "$tmp" created."
loop1=1
# end the inner loop
else
let cnt++ # try the next one
fi
done
fi
done
exit $rc # exit with return code


#every time you run this script with arguments if it finds backup file created by itself

#it will create the next backup with incrementing numbers so the backup can

#more organized


Using TPUT command to change cursor position in a Shell Script,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
# 21/05/2018
# script4
# Subroutines Example
export LINES=$LINES
export COLUMNS=$COLUMNS
#echo $LINES
cls()
{
tput clear
return 0
}
home()
{
tput cup 0 0
return 0
}

bold()
{
tput smso
# no newline or else will scroll
}
unbold()
{
tput rmso
}
underline()
{
tput smul
}
normalline()
{
tput rmul
}
end()
{
#x="${COLUMNS}"-1
let x=$COLUMNS-1

let y=$LINES
#echo x is $x
#echo y is $y
tput cup $y $x
echo -n ""
}
# Code starts here
rc=0
# return code
if [ $# -ne 1 ] ; then
echo "Usage: script4 parameter"
echo "Where parameter can be: "
echo " home - put an X at the home position"
echo " cls - clear the terminal screen"
echo " end - put an X at the last screen position"
echo " bold - bold the following output"
echo " underline - underline the following output"
exit 255
fi
parm=$1
# main parameter 1
if [ "$parm" = "home" ] ; then
echo "Calling subroutine home."
home
echo -n "X"
elif [ "$parm" = "cls" ] ; then
cls
elif [ "$parm" = "end" ] ; then
echo "Calling subroutine end."
end
elif [ "$parm" = "bold" ] ; then
echo "Calling subroutine bold."
bold
echo "After calling subroutine bold."
unbold
echo "After calling subroutine unbold."
elif [ "$parm" = "underline" ] ; then
echo "Calling subroutine underline."
underline
echo "After subroutine underline."
normalline
echo "After subroutine normalline."
else
echo "Unknown parameter: $parm"
rc=1
fi
exit $rc

Saturday, May 19, 2018

Create Numbered backup files from the current working directory given as arguments,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
echo "Create Numbered Backup from files of the current directory given as argument"
if [ $# -eq 0 ] ; then
echo "Usage: sh ./createnumberedbackup.sh filename(s) "
echo " Will make a numbered backup of the files(s) given."
echo " Files must be in the current directory."
exit 255
fi
rc=0 # return code, default is no error
for fn in $*  # for each filename given as arguments

do
if [ ! -f $fn ] ; then # if not found
echo "File $fn not found."
rc=1 # one or more files were not found
else
cnt=1 # file counter
loop1=0 # loop flag
while [ $loop1 -eq 0 ]
do
tmp=bak-$cnt.$fn
if [ ! -f $tmp ] ; then
cp $fn $tmp
echo "File "$tmp" created."
loop1=1
# end the inner loop
else
let cnt++ # try the next one
fi
done
fi
done
exit $rc # exit with return code


Usage:


sh ./createnumberedbackup.sh a1.txt a2.txt

Friday, May 18, 2018

Shell script to watch a process and inform when it ends ,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 18/5/2018
#
echo "this shell script will watch when a process ends"
if [ $# -ne 1 ] ; then
echo "Usage: processwatcher process-directory"
echo " For example: processwatcher /proc/14856 where 14856 is the PID of the  target process"
exit 255
fi
FN=$1
# process directory i.e. /proc/14856
rc=1
while [ $rc -eq 1 ]
do
if [ ! -d $FN ] ; then
# if directory is not there
echo "Process $FN is not running or has been terminated."
let rc=0
else
sleep 1
fi
done
echo "End of processwatcher script"
exit 0

I have given the name of this script as processwatcher.sh,suppose another job or process is going on simultaneously and i want to know when it ends ,my script will serve that purpose when we run it with the Process ID of the target process or job as an argument to this shell script

For example we created this shell script to show the usage of break and continue in shell scripting ,it will run for a certain amount of time

#!/bin/sh
#
# 18/5/2018
#
echo "Break Continue Example"
FN1=/tmp/break.txt
FN2=/tmp/continue.txt
x=1
while [ $x -le 1000000 ]
do
echo "x:$x"
if [ -f $FN1 ] ; then
echo "Running the break command"
rm -f $FN1
break
fi
if [ -f $FN2 ] ; then
echo "Running the continue command"
rm -f $FN2
continue
fi
let x++
sleep 2
done
echo "x:$x"
echo "End"
exit 0


we first run it from the terminal

sh ./breakandcontunue.sh


Now to see what process ID it has while running we need to use the grep command


ps auxw | grep break* | grep -v grep

the last piped section was to filter the grep search which itself acts as a process

the output is like this

sourav   14856  0.0  0.0  12876  2996 pts/1    S+   20:05   0:00 sh ./breakandcontunue.sh

So the PID as we can see is 14856


so in the /proc/folder we should find a folder named 14856 and it will continue to exist while this script/process/job runs

our shell script processwatcher is basically checking the existence of this folder and thus if the process is running with an interval of 1 second with the help of sleep command



 
      

Usage of break and continue statement in a shell script,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 18/5/2018
#
echo "Break Continue Example"
FN1=/tmp/break.txt
FN2=/tmp/continue.txt
x=1
while [ $x -le 1000000 ]
do
echo "x:$x"
if [ -f $FN1 ] ; then
echo "Running the break command"
rm -f $FN1
break
fi
if [ -f $FN2 ] ; then
echo "Running the continue command"
rm -f $FN2
continue
fi
let x++
sleep 1
done
echo "x:$x"
echo "End"
exit 0

You can test the script after creating the necessary files such as continue.txt and break.txt in the /tmp folder


touch /tmp/continue.txt

and the script will continue till x gets 1000000

to stop this use the tab feature in terminal and in a different tab use
touch /tmp/break.txt

The shell script will stop using the break statement

Using Let command in shell script error command not found solved,Linux Teacher Sourav,Kolkata 09748184075

If anyone is trying to learn shell script in ubuntu (in my case ubuntu 16.04), he or she might found out that bash built in commands such as let giving you command not found error ,to solve this you need to understand even if you put the line #!/bin/sh at the top of your script /bin/sh on ubuntu is dash not bash

So to solve this you need to reconfigure dash to not be the default shell

The command to accomplish this is

sudo dpkg-reconfigure dash


press no when asked for whether you like dash to be the default

and then everything should work fine


Source:https://ubuntuforums.org/showthread.php?t=1377218

Thursday, May 10, 2018

Send a message in your phone using VBA and TextLocal API.VBA Teacher Sourav,Kolkata 09748184075

Private Sub Command1_Click()
  
        Dim username As String
        Dim password As String
        Dim result As String
        Dim myURL As String
        Dim Sender As String
        Dim numbers As String
        Dim Message As String
        Dim postData As String
        Dim winHttpReq As Object
        apikey = Text1.Text
        Sender = Text2.Text
        numbers = Text3.Text
        Message = Text4.Text
    
        Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    
        myURL = "https://api.textlocal.in/send/?"
        postData = "apikey=" + apikey + "&message=" + Message + "&numbers=" + numbers + "&sender=" + Sender
    
        winHttpReq.Open "POST", myURL, False
        winHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        winHttpReq.Send (postData)
    
        sendsms = winHttpReq.responseText
        MsgBox (sendsms)
       
    End Sub
   

**For promotional account which is mine the sender should be blank

**Due to TRI NCCP regulation after 9 pm and before 9 am you can not send message (error 192)
   


I followed this tutorial

https://www.youtube.com/watch?v=fc5ZNMXb4Fo

Tuesday, May 8, 2018

WI-FI getting disconnected/Networks not showing up on Ubuntu 16.04 solved ,Linux Teacher Sourav,Kolkata 09748184075


Install rfkill

sudo apt-get install rfkill
then run this command

rfkill unblock all
check if the wifi is working. If not do this

sudo nano /var/lib/NetworkManager/NetworkManager.state
then you will see some settings. Set everything to "true" reboot your system

give this command in terminal

rfkill list
you'll see that some are softblocked and hardblocked. All of them should be "no".

If it's not "no" then you need to somehow turn them to "no". I did this and it worked for me

sudo modprobe -r acer-wmi
cd /etc/modprobe.d
sudo nano blacklist.conf
Then add blacklist acer-wmi as a new line at the end of the file.

then save the file by pressing Ctrl+O ,close it and reboot the system. It should work

Source:https://askubuntu.com/questions/769521/wifi-networks-are-not-showing-in-ubuntu-16-04?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Friday, May 4, 2018

Install PHPMyAdmin after installing Mysql on Ubuntu 16.04

 sudo apt-get update
    sudo apt-get install phpmyadmin php-mbstring php-gettext

After opening PHPMyAdmin if you create a database and open it you may see

CONNECTION FOR CONTROLUSER AS DEFINED IN YOUR CONFIGURATION FAILED

You have to open this file

/etc/phpmyadmin/config-db.php

and see if the configuration is like this

$dbuser='root';
$dbpass='password'; // set current password between quotes ' '
$basepath='';
$dbname='phpmyadmin';
$dbserver='';
$dbport='';
$dbtype='mysql';

save and close the file

restart mysql server by

sudo service mysql stop

sudo service mysql start