Farid Ahmadian / DevOps

Bash Script Cheet Sheet


Simple bash loop example


#!/bin/bash
for i in $(seq 1 2 20)
do
   echo "Welcome $i times"
done

Empty file finder


#! /bin/bash
TEMP_FILE='/var/tmp/empty_file_finder'

find $1 -iname "*" > $TEMP_FILE

for line in $(cat $TEMP_FILE)          
do 
    if [ ! -s "$line" ]
    then
        echo $line 
    fi        
done
rm $TEMP_FILE

Simple sed example


for f in *.php
do
 sed -i  's,SEARCH_STRING,REPLACE_STRING,g' $f
done

Just another sed example


#!/bin/bash
echo -n "what is current main word? (task) "
read current

echo -n "what is future main word? (note) "
read future

for i in $( find . -name "*$current*" ); do
    echo item: $i
    y=$( echo $i | sed -e "s/$current/$future/" )
    echo replaced: $y
    mv $i $y
done

find . -type f -exec sed -i "s/$current/$future/g" {} +

current=$(echo "$current" | sed 's/.*/\u&/')
future=$(echo "$future" | sed 's/.*/\u&/')
echo "now upper case time: "  $current  " with "  $future
find . -type f -exec sed -i "s/$current/$future/g" {} +

Simple backup example


SINIC_BACKUP_PATH="/home/sinic/BACKUP/"
GitLab_BACKUP_PATH="/var/opt/gitlab/backups/*"
YouTrack_BACKUP_PATH="/home/youtrack/teamsysdata-backup/*"

rm -rf $SINIC_BACKUP_PATH"*"
#Backup gitlab and put it into /var/opt/gitlab/backups/
#must run as root or with sudo 
gitlab-rake gitlab:backup:create
mv $GitLab_BACKUP_PATH $SINIC_BACKUP_PATH
mv $YouTrack_BACKUP_PATH $SINIC_BACKUP_PATH
chown -R sinic:sinic $SINIC_BACKUP_PATH

Transfer local backup to server


#!/bin/bash

#Backup transfer from server to local computer
#Remember: you must add your ssh public key in server ssh's authorized_keys
SINIC_BACKUP_PATH="/home/sinic/BACKUP/"
LOCAL_BACKUP_PATH="/home/sinic/work/backup"

#Delete all files that older than one week
find $LOCAL_BACKUP_PATH  -cmin +10080  -exec /bin/rm -rf "{}" \;

rsync -aP [email protected]:$SINIC_BACKUP_PATH $LOCAL_BACKUP_PATH

Change desktop backgroud


feh  --bg-scale '/home/pesarkhobeee/.local/share/eog-wallpaper.png'

Change keyboard layout


#/bin/bash
X=`setxkbmap -print -verbose 10 | grep layout | grep -o -e '[^ ]*$'`
if [ $X = "us" ] ; then
    setxkbmap ir
fi
if [ $X = "ir" ] ; then
    setxkbmap us
fi

ToggleMute


#!/bin/bash
X=`amixer get Master | grep "Playback" | grep -o -e "\[off\]" | tail -n 1`
# it's muted
if [ $X = "[off]" ] ; then
    amixer set Master unmute
else
    amixer set Master mute
fi

BY: Farid Ahmadian
TAG: bash, bash-script, sed, git, back-up
DATE: 2016-01-27 19:36:53


Farid Ahmadian / DevOps [ TXT ]

With many thanks and best wishes for dear Pejman Moghadam, someone who taught me alot in linux and life :)