Bash scripts

Change upper case to lower case

#echo ‘TEST’|/usr/bin/tr -s ‘[:upper:]’ ‘[:lower:]’
test

Work with array

IFS=$’\n’ ##here tells how to devide the output, default is space
##but I want to put each line into a array
files=($(ls ./) ##put file names into an array using ()
for (( i=0;i<${#files[@]};i++ ));do mv $files[$i] $files[$i]_OLD done

Match pattern

if [[ $string =~ “data” ]];do
echo “$string contains data”
done

Find

To avoid files started with “.” in find result

find . -name ‘.snapshot’ -prune -o -name ‘file.mp4’

To delete files older than 7*24h

find /var/tmp -mtime +7 -exec rm -f {} \;

awk & Sed

Calculate sum of the file size

ls -l access_log.2008-12-20*|gawk ‘{a+=$5;} END {print a;}’

 

Edit special lines using regular expression

awk ‘/aaa/ ‘ filename

 

Change file names using sed

##Example: from access_log.2008-12-20.01.gz.1  to access_log.2008-12-20.01.1.gz

for file in `ls access_log.2008-12-20.*`

do

newname=`echo $file|sed ‘s/\(access_log.2008-12-20.[0-9][0-9]\).gz.\([0-9]*\)/\1.\2.gz/’`

size=`ls -l $file|awk ‘{print $5}’`

if [ $size -gt 100 ];then

  echo “$file-> $newname”

fi

mv -v $file $newname

done

bash — if

#!/bin/bash

if [ -n “$1” ]; then
        filename = $1;
else
        filename = `date –date=’1 hour ago’ “+%Y-%m-%d.%H”`;
fi

Compare numbers with -gt -lt -ne -eq

if [ “${size}” -gt 100 ];then
  echo $size
fi

Compare strings with = !=

if [ “${domain}” = “lalife.net” ];then
echo “correct”
fi
(#if [ “${domain}”=”lalife.net” ];then (##this won’t work without space around “=” or “!=”)

When using [[ ]]
if [[ ${domain} = “lalife.net” ]];then
echo “correct”
fi

([ ] needs the variable to be inside of “”)

Match
if [[ ${domain} =~ “lalife.net” ]];then
echo “correct”
fi
([ ] doesn’t work with =~)