# declare the file as a bash script
#!/bin/bash
# debug a script
bash -x script.sh
# variables
name="Bob"
echo $name
# single quotes doesn't output variables
echo '$name'
$name
# double quotes does output variables
echo "$name"
bob
# output commands in a string
echo "`ls`"
index.html
style.css
echo "$(ls)"
# don't include the new lines
echo `ls`
index.html style.css
# output the date
echo "Running backup $(date +'%d/%m/%Y %H:%M')"
Running backup 28/05/2014 12:09
# global variable
echo $USER
# list global variables
env
# script arguments
arg_one=$1
arg_two=$2
# script file path
echo $_
# script process id
echo $$
# previous exit status
echo $?
# check the exit status
grep bob /etc/passwd
echo $?
# condition if grep does find any results
grep bob /etc/passwd
if [ $? -ne 0 ]; then echo "No bob lives here"; fi
if [ -s file ]
then
# file is not empty
else
# file is empty
fi
if ! grep bob /etc/passwd
then
echo "No bob lives here"
fi
# condition flags
-e file # file exists
-s file # file exists and size is greater than zero
-f file # file exists and regular file and not a special file such as a dirctory
-r file # file exists and readable
-w file # file exists and writable
-x file # file exists and executable
-d file # file exists and is a directory
-z string # empty string
-n string # not empty string
# check if an app is installed
if hash mysql 2>/dev/null
then
echo "MySQL is installed"
fi
# check for script arguments
repo_name=$1
repo_desc=$2
if [ -z $repo_name ] || [ -z $repo_desc ]
then
echo 'Where are you arguments?'
exit 0
fi
GREEN='\033[32m'
BLUE='\033[36m'
YELLOW='\033[33m'
NC='\033[0m'
echo -e "${GREEN}So colourful${NC}"
grep user /etc/mysql/debian.cnf
user = debian-sys-maint
user = debian-sys-maint
# only use the last line
grep user /etc/mysql/debian.cnf | tail -n 1
user = debian-sys-maint
# remove sections from a line, using = as a delimiter
grep user /etc/mysql/debian.cnf | tail -n 1 | cut -d"=" -f2
debian-sys-maint
# print the first field out, it ignores spaces
grep user /etc/mysql/debian.cnf | tail -n 1 | cut -d"=" -f2 | awk '{print $1}'
# remove a line with the extact string
grep -v ^Database$
# translate the spaces to new lines
/usr/sbin/mysqld --print-defaults
--user=mysql --pid-file=/var/run/mysqld/mysqld.pid --port=3306
/usr/sbin/mysqld --print-defaults | tr " " "\n"
--user=mysql
--pid-file=/var/run/mysqld/mysqld.pid
--port=3306
# mysql show all the databases (debian)
mysql --defaults-file=/etc/mysql/debian.cnf --execute="SHOW DATABASES"
# find files and chmod each one
find /var/backup/db* -type f -exec chmod 400 {} \;
# replace string 1.9.2 with 2.1.1 in the server.conf file, also backup the file with an extension include the date.
sed --in-place='.$(date +%Y%m%d_%H%M).backup' 's/1.9.2/2.1.1/g' server.conf"
# remove files older than 24 hours
find /var/backups/daily -type f -mmin +1440 -exec rm {} \;