Is it possible to make sandwhich aliases?

I'm looking for a way to make the following alias work for any file name.

alias dim='cd /home/jason/Documents; vim *the desired file*; cd'

I'm wondering if there is a way I could change this alias to make it so that I could type in any file name as such:

dim *the desired file*

And still get the same result. Basically is there a way to call whatever is typed after the alias name into the alias itself? Something like:

alias dim='cd /home/jason/Documents; vim <what is typed after alias>; cd'

Solution 1:

No, you can not do that using shell aliases. You need to use a function.

Here is a simple function to do the job :

dim() {
cd /home/jason/Documents
vim "$1"
cd
}

The function dim will take a file name as argument. You can put this code snippet at the end of your ~/.bashrc file and then run it as:

dim file.txt

Replace file.txt with any file name you want.

To run it from the current shell session, source the ~/.bashrc file first :

. ~/.bashrc

Solution 2:

Not with aliases, use functions instead.

From the Bash man page:

ALIASES

[...] There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used (see FUNCTIONS below).

So your function could be:

function dim () { cd ~jason/Documents ; vim $* ; cd - ;}