1

I'm in my first semester of BASH Scripting and I am having some difficulty. I've taken other programming courses like C++ or Java but the syntax of Bash is killing me. I'd love some advice on this problem. I need to do the following:

  • Extract Today's data from /var/log/secure file
  • Check to see if I have a directory called 'mylogs'
  • If I don't - then create one
  • Check to see if you already have a file matching the current day, month and hour in the ‘mylogs’ directory.
  • If you do, echo to the screen “File exists, nothing written to my log”, and exit. If it doesn’t exist then write today’s data from /var/log/secure to your ‘mylog-month-day-hour’ file. Example (February, 4th at 2pm) output: mylog-02-04-14

I just need help with the syntax portion of the script.

Thanks - I'd love any websites helping out in BASH as well.

Dhunt90
  • 81
  • 1
  • 9

2 Answers2

2
  • Extract Today's data from /var/log/secure file

You could do this ...

grep "^Feb 24" /var/log/secure
  • Check to see if I have a directory called 'mylogs' and If I don't - then create one

You can do this ...

test -d mylogs || mkdir mylogs
  • Check to see if you already have a file matching the current day, month and hour in the ‘mylogs’ directory. (Assuming file names are of the format DDMMHH)

    test -e mylogs/`date +%d%m%H` && echo "I already have a file"

  • If you do, echo to the screen “File exists, nothing written to my log”, and exit. If it doesn’t exist then write today’s data from /var/log/secure to your ‘mylog-month-day-hour’ file. Example (February, 4th at 2pm) output: mylog-02-04-14

Eh you should get the idea by now. You can tackle this one now I think ;) A helpful command to know is man -k <keyword>

Red Cricket
  • 9,762
  • 21
  • 81
  • 166
  • Thanks - my only question is (I've been researching this) is that I need it be run everyday - so running Grep Feb 24 wouldn't work - so is there a variable for just date? – Dhunt90 Feb 25 '13 at 00:31
  • For dates with single-digit day-of-month values, `grep "^Feb 2"` will match 2nd, and 20th-29th... could use e.g. "^Feb 2[^0-9]", or if you knew it was followed by a particular character, look for that e.g. "^Feb 2," or "^Feb 2 ". – Tony Delroy Feb 25 '13 at 04:50
1

First read some bash basics. Then, there are links describing your particular problem.

Community
  • 1
  • 1
Stepo
  • 1,036
  • 1
  • 13
  • 24
  • Thanks - and if I wanted to grab the date from /var/log/secure - would I use grep? – Dhunt90 Feb 25 '13 at 00:19
  • Yep, it's good searching tool. When my server was hacked I was sniffing for details with grep. – Stepo Feb 25 '13 at 00:21
  • grep, sed, awk, cut, find, date, tr, test operators, `>`, `<`, `|` (I am probably leave a few out) are all commands you need to read the manpages for if you want to be proficient in write shell script. – Red Cricket Feb 25 '13 at 01:23