Bash usefull function
Sommaire
- 1 Fichiers & Répertoire
- 1.1 Test si le répertoire est vide
- 1.2 nombre de répertoire d'un repertoire
- 1.3 plus ancien répertoire d'un repertoire
- 1.4 plus récent répertoire d'un repertoire
- 1.5 Test des droits d'un répertoire
- 1.6 Test d’existence
- 1.7 Test si c'est un fichier
- 1.8 sauvegarde un fichier
- 1.9 nettoie les ^M d'un fichier
- 1.10 nettoie les Bom d'un fichier
- 1.11 nettoie tous les fichiers d'un répertoire
- 1.12 ajoute, si besoin, un / à la fin d'un nom de répertoire
- 1.13 test sir url existe
- 2 Système
- 3 Chaîne de caractère
- 4 Cryptage
- 5 Application GIT
- 6 Application PHP
- 7 Application MYSQL
Fichiers & Répertoire
Test si le répertoire est vide
- call isEmptyDir "folder Path"
#return 1 if folder is empty
isEmptyDir()
{
if [ "$(ls -A $1)" ]; then
return 1
else
return 0
fi
}
nombre de répertoire d'un repertoire
- call : countDir "folderPath"
#return nb folder found
countDir()
{
echo $(ls $1/*/ -d | wc -l)
}
plus ancien répertoire d'un repertoire
- call : lastestDir "folderPath"
#return lastest folder
lastestDir()
{
echo $(ls -dt $1/*/ | tail -1)
}
plus récent répertoire d'un repertoire
- call : oldestDir "folderPath"
#return oldest folder
oldestDir()
{
echo $(ls -dtr $1/*/ | tail -1)
}
Test des droits d'un répertoire
- 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 d’existence
- 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 si c'est un fichier
- call : isFile "fileOrFolder"
#reurn f if file, d if folder
isFile()
{
[ -f $1 ] && echo "f"
[ -d $1 ] && echo "d"
}
sauvegarde un fichier
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
}
nettoie les ^M d'un fichier
call : unCtrlM "fileName"
unCtrlM()
{
tr -d '\r' < $1 > temp.$$ && mv temp.$$ $1
}
nettoie les Bom d'un fichier
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;
}
nettoie tous les fichiers d'un répertoire
- 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
}
ajoute, si besoin, un / à la fin d'un nom de répertoire
- call : addSlashToFold "foldName"
addSlashToFold()
{
[[ "$1" == */ ]] && echo "$1" || echo "${1}/"
}
test sir url existe
- call : urlExist "urlAdress"
urlExist()
{
curl --output /dev/null --silent --head --fail "$1" && return 1 || return 0
}
Système
ping un groupe d'ordinateur
#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
gestion des paramètres d'un fichier script
- 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
Demande un choix à l'utilisateur
- 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 si la commande existe
- call : canExec "programCommand"
#return 0 if command exist else return 1
canExec()
{
type "$1" &> /dev/null ;
}
Chaîne de caractère
Trim d'une chaîne
- call : trim str1
trim()
{
echo $1 | sed -e 's/^ *//' -e 's/ *$//'
}
Occurrence d'un caractère
- call : countChar str chr
countChar()
{
nbChar="${1//[^$2]}"
echo ${#nbChar}
}
Chaîne se termine par
- call : enWith "strWho" "strWith"
endWith()
{
[[ $1 == *$2 ]] && return 1 || return 0
}
Chaîne est dans un tableau de donnée
- 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
}
Cryptage
encode en md5
- call : getMd5 {text}
getMd5()
{
hashPass=$(echo -n "password" | md5sum)
hashPass=${hashPass//- }
echo hashPass
}
encode en sha1
- 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
}
IP du serveur GIT
- 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]}
}
mise à jour de la 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}"
}
mise à jour d'un répertoire
- 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
}
installe/met à jour
- 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
}
sélectionne une branche
- 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
installe une 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
changer le mot de passe d'un utilisateur
- call : changeMysqlUserPass {user} {oldPass} {newPass}
changeMysqlUserPass()
{
echo $(mysql -u${1} -p${2} -e "SET PASSWORD FOR '$1'@'localhost' = PASSWORD('$3');")
}