Code Snippet

Just another Code Snippet site

[Bash] How-To

Create a tar.gz file for each file :

for i in *.dbf; do tar -czf $i.tar.gz $i; done

Add datetime in bash history :

echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile

To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}:

#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/$secondString}"    
# prints 'I love Sara and Marry' 

To replace all occurrences, use ${parameter//pattern/string}:

message='The secret code is 12345'
echo "${message//[0-9]/X}"           
# prints 'The secret code is XXXXX'

Show path in bash prompt
Add following line in .bashrc

export PS1="\\u@\\h:\\w\\$ "

Check keyboard input and call associated function:
Script used to ask confirmation before stopping a tomcat instance.

Information like reason, username, datetime are stored in a logfile.

#!/bin/bash

function stopApp(){
	read -p "You are requesting a stop of the application, thanks to provide an explanation : " explanation
	echo `date` "- $USER - " `who am i | awk '{print $1}'` " - Stoping Tomcat... (Reason : $explanation)" >> log.log
	./shutdown.sh
}

while true; do
    read -p "Do you want to stop the application ? (Y/N) : " yn
    case $yn in
        [Yy]* ) stopApp; break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

trim leading and trailing whitespace :

awk '{$1=$1};1'

#Eaxmple :
ip a | grep inet | grep -v "127.0.0.1" | grep -v "inet6" | awk '{$1=$1};1'


, , ,


15 thoughts on “[Bash] How-To

  • Olivier says:

    Zip a folder :

    zip -r data.zip data/
    
  • Olivier says:

    Check free inodes :

    df -ih

    This will take time, but can locate the directory with the most files

    find . -xdev -type f | cut -d "/" -f 2 | sort | uniq -c | sort -n
  • Retry function :

    ## ###################################### ##
    ## Retry function
    ## ###################################### ##
    retry() {
        local -r -i max_attempts="$1"; shift
        local -r cmd="$@"
        local -i attempt_num=1
        until $cmd
        do
            if ((attempt_num==max_attempts))
            then
                echo "Attempt $attempt_num failed and there are no more attempts left!"
                return 1
            else
                echo "Attempt $attempt_num failed! Trying again in ${attempt_num}0 seconds..."
                sleep $((attempt_num++))0
            fi
        done
    }
    
  • Check Defunct process :

    ps -ef | grep '<defunct>'
    

    Kill defunct process (based on parend ID)

    ps -ef | grep '<defunct>'| grep -v grep | cut -b15-20 | xargs kill -9 
    
  • Substring by index (1-based)

    echo "abcdefghi" | cut -c2-6
    bcdef
    
    A="abcdefghi"
    echo ${A:0:3}
    abc
    
  • Uppercase :

    $ name='fahmida'
    $ echo $name
    fahmida
    $ echo ${name^}
    Fahmida
    $ echo ${name^^}
    FAHMIDA
    

    Lowercase:

    $ name='TOTO'
    $ echo $name
    TOTO
    $ echo ${name,}
    tOTO
    $ echo ${name,,}
    toto
    
  • Browse subdir

    LIST_OF_DIRS=`find . -name *.log | cut -d '/' -f -6 | awk '{$1=$1};1' | uniq`
    for DIR in $LIST_OF_DIRS
    do
        pushd $DIR    
        prefix=`echo $DIR | cut -d '/' -f 2`
        zipLogs /tmp "${prefix}"    
        popd
    done
    
  • Array :

    Add element to an arrat

    toBePushed=()
    
    toBePushed+=("A")
    toBePushed+=("A1")
    toBePushed+=("A2")
    toBePushed+=("A3")
    

    Loop on array

    for i in "${toBePushed[@]}"
    do
        echo "Pusing  ${i}"
    done
    

    Print array

    printf '%s\n' "${toBePushed[@]}"
    
  • sed :

    sed -i 's%/my/oldpath%/my/new/path%g' my_file.txt
    
  • Remove duplicate from a file :

    cat my_file.txt | sort | uniq > my_file_uniq.txt
    
  • Test zip/jar integrity

    unzip -t MY_FILE.zip
    
  • see output of unattached process :

    cat /proc/<PID>/fd/1
    

    (tail is not working properly)

  • list all mount points:

    findmnt
  • log with color

    Yellow

    function logYellow {
        YELL='\033[1;33m';NC='\033[0m' # No Color
        DATE=`date "+%Y-%m-%d %T"`
        printf "${YELL}${DATE} - $1${NC} \n"
    }
    
    function logGreen {
        GREEN='\033[1;32m';NC='\033[0m' # No Color
        DATE=`date "+%Y-%m-%d %T"`
        printf "${GREEN}${DATE} - $1${NC} \n"
    }
    
  • Using env variable in sed:

    sed 's@xxx@'"$PWD"'@'
    

Leave a Reply to OLIVIER COMBE Cancel reply

Your email address will not be published. Required fields are marked *