8

There are several files I work with often. For instance some configuration files or log files. Let's say the Apache log file. I often want to tail or grep it. Instead of writing:

tail -50 /var/log/apache2/error_log

I prefer to write

tail -50 apachelog

So that apachelog functions as an alias for this filename. But if I define an alias in my bashrc, it needs to be a whole command; it (apparently) can not be an alias for a filename so that you can reference it later. Is there a way to achieve this?

NOTE: I have a large variety of files and a large variety of different commands I want to run, so creating functions or aliasses for all of those different options will not be my preferred solution.

5 Answers 5

12

You can define a variable, and use a $ to recall its value:

apachelog=/var/log/apache2/error_log
tail -50 $apachelog

You're not going to do better in bash. In zsh, you can define global aliases, that are expanded everywhere on the command line:

alias -g apachelog=/var/log/apache2/error_log
tail -50 apachelog

But I don't recommend it, because now if you ever want to pass the string apachelog as an argument to a command, you need to remember to quote it.

1
  • Good answer, especially the "Do not recommend this" part. That sounds like a recipe for disaster with a poor alias name choice... Commented Nov 28, 2011 at 14:09
7

You could create a function and write your command "backwards"

apachelog() {
  "$@" /var/log/apache2/error_log
}

apachelog tail -50
2

An alias to a directory is link. That's why one possibility is to create a bunch of links to the files of interest in one directory. Then alias rtail to tail so that it looks for files in that directory.

1

For bash aliases, the documentation states:

If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.

Notice the trailing space in the definition of the tail alias:

alias tail='tail '
alias apache=/var/log/apache2/error_log

tail apache

This should work in any standard shell, not just bash. Note that you will not be able to use options to tail from the command-line.

1
  • Note that the user in the question seems to want to provide options for tail (and that it's unclear whether these options are static or not). Commented Oct 9, 2022 at 7:38
0

Put this in your ~/.bashrc

 alias tailapache='tail -50 /var/log/apache2/error_log'

do a source ~/.bashrc or start a new bash session...

then you just need to type tailapache

You must log in to answer this question.