Bash Examples
# Invoke last option from previous command:
mv debug.log* /var/log/foo/debug/
cd !$
cd /var/log/foo/debug/
# home directory backup:
for i in $(ls /home/);
do
echo working on home $i
tar -czf $i.tar.gz /home/$i
done
# keep an eye on something:
while true ; do ; sleep 60 ; df -m ; done
# log monitor (Pulls out the last 20 relevent entries and checks if over 90% result in a horrible error message)
ERRORCOUNT=`grep "relevant log entry" /var/log/appname/foo.log | tail -20l | grep "horrible error message" | wc -l`
if [ "$ERRORCOUNT" -gt "17" ]; then
echo "/var/log/appname/foo.log error count CRITICAL, restart appname immediately"
exit 2
else
echo "/var/log/appname/foo.log OK"
exit 0
fi
# file renamer
#!/bin/bash
criteria=$1
re_match=$2
replace=$3
for i in $( ls *$criteria* );
do
src=$i
tgt=$(echo $i | sed -e "s/$re_match/$replace/")
mv $src $tgt
done
# loop + if/then
for ((i=1; i<16; i++)); do
if [ $i -lt 10 ]; then
echo 0$i ;
else
echo $i ;
fi
done
# arithmetic for loop example 1 (making 100 copies):
for ((i=1; i<101; i++)); do cp picture.jpg picture_$i.jpg; done
# arithmetic for loop example 2 (creating 100 empty test files):
for ((i=100; i<200; i++)); do touch $i.txt; done
# convert all files in a directory to lower case:
for file in * ; do [ -f $file ] && mv -i $file `echo $file | tr '[A-Z]' '[a-z]'`; done
# rename all files to a series of incrementing numbers:
export counter=1
for file in *.jpg; do mv $file "$counter.jpg"; let "counter+=1"; done
# file rename example 1 (renaming test.txt to foo-test.txt):
for file in *.txt; do mv "$file" "foo-$file"; done
# file rename example 2 (renaming test.txt to test-foo.txt):
for file in *.txt; do mv "$file" "$(basename "$file" .txt)-foo.txt"; done
# go through a file line by line:
cat /tmp/list-of-files |
while read line
do
if [ -f "$line" ]; then
ls -al "$line"
else
echo ERROR - File does not exist - $line
fi
done
# Loop through list:
COLORLIST="blue green red"
for ITEM in $COLORLIST
do
echo "The color is $ITEM";
done