This may not be the "best" solution, but one I'm quite comfortable with. I've always liked using Python for my repetitive tasks that it would take too long to do properly in bash, and this definitely fits the bill.
The idea is to check if /sbin
is present in $PATH
, delimited by the start or end of the string, or a colon. grep
or even extended test ([[
) can do this for you pretty easily, but for a general solution, where the path of interest may have regex control characters, or you would have to escape parts of the string. It's much easier in Python than in bash: Is it possible to escape regex metacharacters reliably with sed. So I use a script like this (which actually avoids almost all manual parsing):
inpath
#/usr/bin/env python
"""
Checks if the sole argument is in the PATH.
Returns 0 if yes, 1 if no. It is an error to pass in more
than one command-line argument.
"""
import sys
from is import get_exec_path
from os path import abspath, normcase
if len(sys.argv) != 2:
raise ValueError('Exactly one command line argument must be provided')
path = [normcase(abspath(p)) for p in get_exec_path()]
sys.exit(sys.argv[1] not in path)
This can be implemented in any number of languages more simply than in bash; I just happen to be familiar with Python. It should work with any sane version, probably before even 2.6. It's written to run on Unix or Windows, although I'm going to guess that it's not really useful on the latter. Use it like this:
if inpath /sbin ; then
echo "export PATH=\"$PATH:/sbin\"" >> ~/.bashrc
fi
Or
inpath /sbin && echo "export PATH=\"$PATH:/sbin\"" >> ~/.bashrc