Pass parameters to Bash Alias command

pass console command parameters to bash alias command- like hammer bashes a nailI use BASH aliases extensively throughout my DEV environments and it saves me a lot of time. One specific I use is “cdv” that’s shorthand for CD to VirtualHosts which in most cases could be as simple as /var/www or in some cases could be very long path, especially on shared DEV environments like /var/www/dev/vhosts/mylongusername.

So “cdv” is very handy but it has some constraints. Imagine you have multiple projects and you have to switch though them very often so we have site1, site2 and site3 in that case it’d be quite handy to be able to pass parameters to our alias but that doesn’t work for aliases on Unix unless you use small trick, instead of alias you can use a function, yes function. Here is an example:

function cdv () {
if [[ -z $1 ]]
then
  cd /var/www
else
  cd /var/www/$1
fi
}

Simple as that. First we name the function as the alias we’d like to use, after that we check for a parameter and if it’s not null and finally execute the appropriate command with or without parameter. Example call in our case would be “cdv site1/public” or just “cdv site1“.

It's only fair to share...Buffer this pageShare on Facebook0Tweet about this on TwitterShare on Google+0Share on LinkedIn0Share on Reddit0Pin on Pinterest0Email this to someone
About

Just a guy with strong interest in PHP and Web technologies

Posted in BASH, Unix Tagged with: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*