Programmer's Blog

Programmer's reference

Category Archives: Shell

[Shell] remove a lines of text if matches

if grep -Fxq "keyword" file.txt
then
sed -i '/keyword/d' file.txt
fi

[Mysql] Shell script for running SQL

login="mysql -uroot john"

//run sql statement
login -e "select * from mytable"

//run sql statement with variables
sql="insert into mytable (col1,col2) values ('$var1','$var2');

$login -e "$sql"

[shell] Shell functions

_showHelloWorld(){
echo "Hello World!"
}

_showHello(){
echo "Hello!"
}

while [ $choice != 0 ]
do
echo "Enter choice 1. Hello World, 2.Hello";
read choice

if [ $choice == 1 ]
then
_showHelloWorld()
else
_showHello()
fi

done

[shell] Logical comparison

if [ "$choice" == "Y" ] || [ "$choice" == "y" ];
then
....
fi

[shell] Data Checking from read

read TON
if [[ ! $TON =~ ^[A-Za-z0-9]$ ]]; then
 echo "$TON is not alphanumeric"
 return
fi

//perform regex check

[Shell] Find bin path using env

In the previous example of using expect the bin file is specified using the following syntax

#!/usr/bin/expect

If the path to expect is not found, try

#!/usr/bin/env expect

This will cause the execution to search for the excutable

[Shell] Repeat execution at certain time interval

SCRIPT_START_TIME=`date +%s`
TOTAL_RUNTIME=2  //how many times you want to run your script once start execution
SLEEP_TIME=10   //time interval you want to run the script

EXECUTION_END_TIME=0
 TOTAL_ELAPSED_TIME=0
function startExecution()
{
 //Things you want to do here
 }
until [ x = "true" ]
 do
startExecution
 echo “script running since : $TOTAL_ELAPSED_TIME seconds”
 sleep $SLEEP_TIME
 EXECUTION_END_TIME=`date +%s`
 TOTAL_ELAPSED_TIME=`expr $EXECUTION_END_TIME – $SCRIPT_START_TIME`
if [ $TOTAL_RUNTIME -lt $TOTAL_ELAPSED_TIME ]
 then
 break
 fi
done
echo “script execution complete”

[Linux] Mysql startup shell script

Execute below script as mysql user to start mysql.

//————————

./bin/mysqld_safe 
--defaults-file=/usr/local/mysql/my.cnf 
--basedir=/usr/local/mysql 
--datadir=/var/log/.....<require log path>....../mysql 
--user mysql

Bash setting for MYSQL_HOME (user: mysql)

The below script is added to ~/.bash_profile for referencing mysql lib.

//—————————-

MYSQL_HOME=/usr/local/mysql
PATH=$PATH:$HOME/bin:$MYSQL_HOME/bin
export PATH