Alias vs Shell script
Often times we *ix users want to make a command easier when we type it often. To create a shell script for all of these simple things is just a bit overkill, but creating an alias does not always do what you want. Aliasses can’t take parameters without having a delimter… Here is how to get it do work.
If you could do it with more ease in a shell script is up to you to descide…
Introduction into alias
In the .bashrc
or .profile
or for the zsh user under us .zshrc
you can create alias definitions that will be available for every terminal session. How to create an alias is very easy:
e.g. open one of the above files (if you do not know which one go for .profile
that will work on most *ix machines)
add something like:
|
|
now every time you open a new terminal session (the aliasses have to be activated) you can type ls
and get the result of ls -lsa
because that is what the alias does.
alias with Parameters
So what do I mean with parameters in this context? Take the example above if you would do ls /tmp
it will perform ls -lsa /tmp
and that is exactly what you want, but what if you have a special cd
command alias like alias dev=cd /some/dev/folder/
. Now if you would only perform dev
it would change the directory to /some/dev/folder/
, but if you did dev cool/project
it would try to do the following:
|
|
Note the space in the path. This will fail bacause it is not a valid command. This is what is meant with parameter in this context. This you can not fix with a standard alias command. So how to fix this…
Enter functions
To get the above special dev
command to work open the .profile
again and make the following function:
|
|
Save and close the file and open a new terminal session or do the following in the current session . ./.profile
or source ./.profile
this will run .profile
in the current session in the current shell. Most of the time it is faster to just start a new session :-)
now you can run cd cool/project
an it wil try to perform cd /some/dev/folder/cool/project
without the space in the path. It will of course only work if the path actually exists.
If you know a better way please let me know in the comments below
Update 2018-01-19
I just learned that you can call shel functions directly. So we could eliminate the alias middle man completely by doing the following:
Just add this to your .profile and use it 😂
|
|