In the 21st century, especially if you're targeting machines that are likely to have bash or zsh, you can count on type
being available. (It didn't exist in extremely old unices, as in, from the 1970s or early 1980s.) You can't count on its output meaning anything, but you can count on its returning 0 if there is a command by that name and nonzero otherwise.
which
isn't standard and is unreliable in practice. type
is the recommended alternative. whereis
suffers from the same problems as which
and is less common. whence
is specific to ksh and zsh.
When that's possible, it would be more reliable to test the existence of a command and test whether its behavior looks reasonable. For example, test the presence of a suitable version of bash by running bash -c 'somecommand'
, e.g.
# Test for the `-v` operator (which appeared in bash 4.2)
if bash -c 'test -v HOME' 2>/dev/null; then …
Today you can count on almost everything in the Singe UNIX specification version 2 (except for exotic stuff like Fortran and SCCS, which are optional anyway). You can count on most of version 3, too, but this isn't completely implemented everywhere yet. Version 4 support is sketchier. If you're going to read these specs, I recommend reading version 3, which is a lot more readable and less ambiguous than version 2.
For examples as to how to detect system specificities, look at autoconf and at configure
scripts of various software.
See also Resources for portable shell programming for more tips.
Not exactly what you asked but I use s to run scripts. So for example if I have a file ~/Scripts/run-stuff.sh I can type s run-stuff.sh and it will run the script. It will also do tab-completion of the script name. The only thing it doesn't do is handle sub-directories in the scripts directory.
# Completion for s (scripts)
_s_comp() {
if [ $OS = "mac" ]; then
local LS=gls;
else
local LS=ls;
fi
reply=(`$LS --ignore-backups $HOME/Scripts/`);
}
compctl -K _s_comp s
It's possible that you may also need an alias like alias s="$HOME/Scripts
Edit: note that this will work regardless of what directory you are currently in.
Best Answer
Contrary to
bash
,zsh
doesn't read.zshrc
when running commands overssh
. So if you mess up yourzshrc
, you can always do:from another machine to put your
.zshrc
out of the way.If you want to test a zshrc, you can put it in another directory and run
zsh
as:to run zsh with that
.zshrc
(or.zshenv
or.zprofile
/.zlogin
/.zlogout
withzsh -l
).You can also login with that ZDOTDIR over ssh with: