sebastiansibelle
sebastiansibelle

Reputation: 25

Difficulty running a Perl script as a Bash alias

To format my apache error_log so that it is more pleasurable to look at I have written a quick and dirty perl script.

tail -f /var/log/apache2/error_log | perl -ne 
  '($timeStamp, $error, $hostName, $message) = 
      /^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i; # Parse log
   ($day, $month, $date, $time, $year) = 
      $timeStamp =~ m/(\S*) (\S*) (\S*) (\S*) (\S*)$/; # Extract the timestamp
   $message =~ s/, referer: (.*)$/\./;  # Strip the referer references
   $message =~ s/\\n/\n/g; # Replace literal new lines to expand object dumps
   print $time . " " . $date . " " . $month . " | " . $message ."\n";'

I want to add the script to a Bash alias so that I can call it easily from terminal.

e.g.

alias te=tail -f /var/log/apache2/error_log | perl -ne '($timeStamp, $error, $hostName, $message) = /^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i; ($day, $month, $date, $time, $year) = $timeStamp =~ m/(\S*) (\S*) (\S*) (\S*) (\S*)$/; $message =~ s/, referer: (.*)$/\./; $message =~ s/\\n/\n/g; print $time . " " . $date . " " . $month . " | " . $message ."\n";'

Obviously escaping quotes starts to get messy. I've also tried putting the perl script in its own file and running that as an alias but I want to avoid having to run a script outside of the .bash_profile file for portability.

How can I use the perl script as a bash alias/function? Or am I coming at this from totally the wrong direction?

Upvotes: 2

Views: 605

Answers (2)

ikegami
ikegami

Reputation: 386426

Change

alias te=tail -f /var/log/apache2/error_log | perl -ne '...'

to

alias te='tail -f /var/log/apache2/error_log | perl -ne '\''...'\'''

Upvotes: 0

ruakh
ruakh

Reputation: 183484

You should definitely use a function instead of an alias:

function te ()
{
    tail -f /var/log/apache2/error_log \
    | perl -ne \
       '($timeStamp, $error, $hostName, $message) = 
          /^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i; # Parse log
        ($day, $month, $date, $time, $year) = 
          $timeStamp =~ m/(\S*) (\S*) (\S*) (\S*) (\S*)$/; # Extract the timestamp
        $message =~ s/, referer: (.*)$/\./;  # Strip the referer references
        $message =~ s/\\n/\n/g; # Replace literal new lines to expand object dumps
        print $time . " " . $date . " " . $month . " | " . $message ."\n";
       '
}

Upvotes: 6

Related Questions