Saturday, 6 July 2019

How to make bash alias invocation conditional on PWD?


I currently have this alias:


alias cmakerel='cmake -DCMAKE_BUILD_TYPE=Release -Wno-dev ../../ && make -j4'

Essentially, it will call cmake to do an out-of-source build from PWD. It works fine, but as-is, it can be run from nearly anywhere (which I don't want).


How do I modify this alias so that it runs if and only if the string bld is in my present working directory?


I need this change because without it, I sometimes accidentally invoke this command from the tst directory or some other directory where I just cause a total mess.



Answer



From man bash:



For almost every purpose, aliases are superseded by shell functions.



So make it a shell function.


function cmakerel {
if expr match "$PWD" '.*bld.*' >/dev/null ; then
cmake -D....
else
echo "Wrong directory!"
fi
}

It's a regular expression you can adjust to your needs.


No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...