I have this bash function which I am trying to use to install a command line tool if it's not already in the PATH:
ncf(){
if ! type -f ncf &> /dev/null || ! which ncf &> /dev/null; then
echo "Installing NPM package '@oresoftware/ncf' globally...";
npm i -s -g '@oresoftware/ncf' || {
echo -e "Could not install NPM package '@oresoftware/ncf' globally." >&2
echo -e "Please check your permissions to install global NPM packages." >&2
return 1;
}
fi
command ncf $@;
}
I have a couple of questions - is type -f ncf
and which ncf
redundant? Right now, I am checking to see if either of them exits with non-zero - if I either one does, I reinstall (at least that's what I think the code is doing).
My other question is - will &>
work for bash versions older than 4, or other shells like sh, ksh, zsh, etc? Is there another construct I should use that's more cross platform than &>
?
PATH
in the script so that it includes the directory where the program ought to be found? If that directory is not inPATH
, you won't be able to start it no matter how much you install it. Also, quote$@
, and you don't need;
at the end of statements if there is no other statement afterwards on the same line. – Kusalananda Jun 24 '18 at 12:23$@
, the shell will perform word splitting and filename globbing on its individual elements. You should always quote all expansions (there only a couple of cases where you don't have to, but it's a good rule of thumb to do it everywhere). – Kusalananda Jun 24 '18 at 20:33