Posts Tagged ‘bash’

As im trying to learn bash scripting its easier if you have a little idea of a script that can be useful to you. For this example I want to backup a set of files/directories and have the script email me with the date, contents of the tar and the time it took to run the process…not as easy as it looks due to the “time command” outputting to stderr. The script can then be used as a cron job.

#!/bin/bash

set -eset -u

DATESTAMP=`date ‘+%d_%m_%Y-%H%M’`#Date will appear in day_month_year-hour&min formatEMAIL=”user@uni.edu.au”#Define an email address for mail to useSUBJECT=”Backup completed for PC-HTPC $DATESTAMP” #Create a subject for the mail including the date defined aboveARCHIVE=”backup_$DATESTAMP.tar.gz” #Create a name for the tarfile including the date defined aboveBODY=`(time tar -cvpzf $ARCHIVE test*) 2>&1`#The tar command (including being timed) and redirecting stderr to stdout

echo -e “$ARCHIVE\n\n$BODY” | mail -s “$SUBJECT” “$EMAIL” #Using the variables archive and body and using the mail command to send the email

So you have the following list of email addresses in the syntax user@uni.edu.au and you want to strip out everything after the @ sign leaving you will a list of usernames. The user names need then to be on one line only.

So for example if the file called “email_list” looked like this:

test1@uni.edu.autest2@uni.edu.autest3@uni.edu.au

To get the first part working:

# cat email_list | sed ‘s/@.*//’

Meaning everything after the @ replace with nothing.

You will get a list like this:

test1test2test3

….but we want the output all on one line to be able to copy and paste it:

Now we are using the first function (function list_src_dirs) in the next function list_src_dirs_perm_err, getting further into the output we actually need.

sed -nr ‘/\t(source|sys)\t/p’ (-n output the following filter -r extended sed) this line prints the lines which have source or sys as the group (word preceeded with a tab)

sed -r ‘/^277[05]/d’ – excludes the following numbers that start from the beginning of the line (^) 2770 or 2775, this is looking at the permissions octal output. Worth remembering that sed looks at the whole line as the output.

sort -k 2 – sorts the second key (second column) which in this case is the username, making the output in alphabetical order.

Ive started to learn bash scripting and have decided to document it on my blog. Its mainly for my reference but I guess it could also be useful for other beginners. Im not doing anything fancy so dont judge 🙂

The idea behind the script is to run on redhat source directories/files to identify which have the wrong user/group permissions and which files are checked out for longer than expected.

Ill put all the explanations in red so they are easy to read, they are currently not part of the script.

SCRIPT 1.0

#!/bin/bash

set -e #If an error occurs, the script will stop)
set -u #reports if there are any undefined variables)