Bash usefull function

From FroggDev - En
Jump to: navigation, search

Files & Folder

Test folder is empty

  • call isEmptyDir "folder Path"
#return 1 if folder is empty
isEmptyDir()
{
if [ "$(ls -A $1)" ]; then
    return 1
else
    return 0
fi
}

count folder in folder

  • call : countDir "folderPath"
#return nb folder found
countDir()
{
echo $(ls $1/*/ -d | wc -l)
}

get most recent folder in folder

  • call : lastestDir "folderPath"
#return most recent folder
lastestDir()
{
echo $(ls -dt $1/*/ | tail -1)
}

get oldest folder in folder

  • call : oldestDir "folderPath"
#return oldest folder
oldestDir()
{
echo $(ls -dtr $1/*/ | tail -1)
}

Test folder rights

  • call : chkPerm "folderPath"
#return 0 if can write, else return 1 + error message
chkPerm()
{
tmpHasErr=0
test=$(touch "$1" 2>&1)
if [[ ! -z $test ]]; then
   echo " [ ERROR ] Write permission is NOT granted on $1"
   tmpHasErr=1
fi
return $tmpHasErr
}

Test existance

  • call : exist "thisFileorFolder" "inThePath"
#File/Folder exist return 0 else return 1
exist()
{
if [ -$1 $2 ]; then 
	echo " => $2 Exist"
	return 0
else
	echo -e " => $2 is missing !";
	return 1
fi
}

Test is a file

  • call : isFile "fileOrFolder"
#reurn f if file, d if folder
isFile()
{
[ -f $1 ] && echo "f"
[ -d $1 ] && echo "d"
}

Backup a file

call : bckFil {fileName}

# Create a backUp file as .origin from original file, if exist save last config to .origin.last
bckFil()
{
if [ -f $1 ]; then 
	if [ -f $1.origin ]; then	
		cp $1 $1.origin.last
	else
		cp $1 $1.origin
	fi
else
	echo " [ WARN ] $1 don't exist, cannot be backuped "
fi
}

clean ^M from file

call : unCtrlM "fileName"

unCtrlM()
{
tr -d '\r' < $1 > temp.$$ && mv temp.$$ $1
}

clean Bom from file

call : unBom "fileName"

# clean "<<1/4*" from file
unBom()
{
iconv -c -f utf8 -t ISO88591 $1 | iconv -f ISO88591 -t utf8 > temp.$$ && mv temp.$$ $1;
}

clean all files from a folder

  • call : cleanDir "dirName"
#clean all files from
cleanDir()
{
for file in $1/*
	do
	if [ -f $file ]; then
		unBom $file
		unCtrlM $file
	else
		cleanDir $file 
	fi
done
}

add a slash at the end of a foldername

  • call : addSlashToFold "foldName"
addSlashToFold()
{
[[ "$1" == */ ]] && echo "$1" || echo "${1}/"
}

test if url exist

  • call : urlExist "urlAdress"
urlExist()
{
curl --output /dev/null --silent --head --fail "$1" && return 1 || return 0
}

System

ping computers

#default scan
ADRESS="192.168.0."
#Get parameter if exist
[ ! -z $1 ] &&  ADRESS=$1
#Start scanning
for i in {1..254} ;do (ping ${ADRESS}${i} -c 1 -w 5 -i 0 >/dev/null && echo "${ADRESS}${i} IS UP" &) ;done

bash file parameters management

  • call : bash example.sh -param1:value1 -param2:value2 -param3:value3 -param4:value4
for params in $*
do
	IFS=: val=($params)
	case ${val[0]} in
		"-param1")
			#Code To Execute
		;;
		"-param2")
			#Code To Execute
		;;
		"-param3")
			#Code To Execute
		;;
		"-param4")
			#Code To Execute
		;;
	esac
done

Prompt User Choice

  • call : makeachoice "example question"
#return 1 if user accpeted else return 0
makeachoice()
{
userChoice=0
while true; do
	read -p " [ Q ] Do you wish to $1 ?" yn
	case $yn in
		y|Y|yes|YES|Yes|O|o)userChoice=1;break;;
		n|N|no|NO|No)userChoice=0;break;;
		* )echo " [ ERROR ] '$yn' isn't a correct value, Please choose yes or no";;
	esac
done
return $userChoice
}

Test command exist

  • call : canExec "programCommand"
#return 0 if command exist else return 1
canExec()
{
type "$1" &> /dev/null ;
}

Strings

Trim a string

  • call : trim str1
trim()
{
echo $1 | sed -e 's/^ *//' -e 's/ *$//'
}

Char occurrence

  • call : countChar str chr
countChar()
{
nbChar="${1//[^$2]}"
echo ${#nbChar}
}

String End With

  • call : enWith "strWho" "strWith"
endWith()
{
[[ $1 == *$2 ]] && return 1 || return 0
}

Test string in array

  • call : IsInArray (str1 str2 str3) "str3"
#return 1 if is in array else return 0
IsInArray()
{
#replace $1 param by FOUND if has been found in $2 array
arrTmp=${2/${1}/FOUND}
#if both arrays are equals then return 0 else return 1
[ "${arrTmp[*]}" == "${2}" ] && return 0 || return 1
}

Test Versionning

  • call : checkVersion "version1" "version2"
#check if version of $1 > $2
checkVersion()
{
#add shell option not sensitive
shopt -s nocasematch
if [ $1 = *beta* -o $1 = *alpha* -o $1 = *gamma* ];then
	return 2
else
	vSort=`printf "$1\n$2" | sort -V`
	vArr=(${vSort//\n/ })
	if [ ${vArr[1]} = $1 ];then
		return 0
	else
		return 1
	fi
fi
#remove shell option not sensitive
shopt -u nocasematch
}

Encryption

md5 encode

  • call : getMd5 {text}
getMd5()
{
hashPass=$(echo -n "password" | md5sum)
hashPass=${hashPass//- } 	
echo hashPass 
}

sha1 encode

  • call : getSha1 {text}
getSha1()
{
hashPass=$(echo -n "password" | openssl dgst -sha1)
hashPass=${hashPass//(stdin)= } 
echo hashPass 
}

Application GIT

test GIT

  • call : gitExist
gitExist()
{
exist=0
if git status &> /dev/null;then
	#Git has been found
	exist=1
fi
return $exist
}

server GIT IP

  • call : getGitIp
getGitIp()
{
#Get server IP Adress from Git configuration
srvOriginGit=$(git config --get remote.origin.url)
IFS='@' read -a arraySrv <<< "$srvOriginGit"
IFS=':' read -a arraySrv2 <<< "${arraySrv[1]}"
return ${arraySrv2[0]}
}

update version

  • call : getNewGitVersion
getNewGitVersion()
{
#get last version
oldVersion=$( git tag | tail -1 )
oldVersion=9998
#split it
arrVersion=( ${oldVersion//./ } )
#get after . version part
subVersion=$(expr ${arrVersion[1]} + 1)
#get before . version part
preVersion=${arrVersion[0]//v/}
#check subversion
if [ $subVersion -eq 9999 ];then 
	subVersion=0
	preVersion=$(expr ${preVersion} + 1)
fi
#format subversion
subVersion=$(printf "%04d\n" $subVersion)
#return
return "v${preVersion}.${subVersion}"
}

update folder

  • updateGitFolders {mainFolder} {excludeFolder}
updateGitFolders()
{
for commonFold in ${1}*;do
	#not for common folder who is a basic wiki folder
	if [ ! "${1}${2}" = $commonFold ];then
		title "$commonFold" "3"
		cd $commonFold
		#if is a git
		if [ -d ".git" ];then 
			#clean uncommitted file/folder
			git clean -fd
			#try to pull
			if git pull &> /dev/null;then
				good "$commonFold updated" 
			else
				#if can't pull, force to remove local changes
				git fetch --all
				git reset --hard origin/master
				if git pull &> /dev/null;then
					good "$commonFold updated" 
				else
					err "error occurred while pulling $commonFold"
					warnList="${warnList}\n- cannot update $commonFold"
				fi
			fi
		else
			good "$commonFold skipped : not a git repository" 
		fi
	fi
done
}

install/update

  • call : updateGit {destinationFolder} {repoUrl}
updateGit()
{
exist "d" "${1}"
if [ $? = 0 ];then
	check "Cloning git repo"
	git clone "${2}" "${1}"
else
	check "Updating git repo"
	cd ${1}
	git checkout master
	git pull
fi
}

select a branch

  • call : chooseGitVersion (need to be in a git folder)
#Ask user to choose a version selected in available version
chooseGitVersion()
{
#get all version
gitVersions=$(git tag -l | sort -V)
currVersion=$(git describe --abbrev=0 --tags)
#ask if start script
makeachoice "use master branch version : ${currVersion}"
if [ $? = 0 ];then
	#display all version
	check "This is the list of version :"
	echo ${gitVersions}
	while true; do
		read -p " [ Q ] Type the version you want to install : " ver
		#check if version exist in the git version list
		testIsInArray "$ver" "$gitVersions"
		[ $? = 0 ] && err "${ver} not found in version list" || break
	done
	#check out the selected branch
	cd ${FoldOptWikiGit}
	git checkout -b REL${ver}
	good "${ver} branch has been selected"
else
	#use master branch
	cd ${FoldOptWikiGit}
	git checkout master
	good "master branch has been selected"
fi
}

Application PHP

install Extension

  • call : installPhpExt {extName} {extAptGet}
installPhpExt()
{
touch tmpTest.php
echo -e "#!/usr/bin/php\n<?php\nif(!extension_loaded('${1}')){echo '0';}else{echo '1';}\n?>" >  tmpTest.php
tmpVal=$(php tmpTest.php)
rm tmpTest.php
if [ $tmpVal = 0 ];then
	#if not installed ask user to install it
	makeachoice "install [${1}] PHP extension"
	if [ $? = 1 ];then
		#si error faire un "apt-get update" avant
		apt-get install ${2}
		service apache2 restart
	fi
else
	good "PHP Extension ${1} already installed"
fi
}

Application MYSQL

change user password

  • call : changeMysqlUserPass {user} {oldPass} {newPass}
changeMysqlUserPass()
{
echo $(mysql -u${1} -p${2} -e "SET PASSWORD FOR '$1'@'localhost' = PASSWORD('$3');")
}