How to set an alias for a specific file or directory?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

You could create a function and write your command “backwards”

apachelog() {
  "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ad89ed">[email protected]</a>" /var/log/apache2/error_log
}

apachelog tail -50

Method 3

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.

Method 4

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”


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x