No need to use a bash array, tr
'ing the ':'
with ' '
will work just fine in a for loop.
#!/bin/bash
#
# Invoke as ./findcmd command
#
# Check for argument
if [[ $# -ne 1 ]]
then
echo 'usage: ./findcmd command'
exit 1
fi
f=$1
# No need to check the $# again, there's at least one arg and other will be ignored..
# Otherwise you can wrap this in a loop and keep shift'ing args and checking one by one
pathlist=`echo $PATH | tr ':' '\n'`
for d in $pathlist;
do
#echo command is your friend
#echo "Checking for $f in $d"
path="$d/$f"
if [[ -f "$path" && -x "$path" ]]; then
# PATH is not recursive, therefore no need to use find command
# Simply checking that the file exists and is executable should be enough
echo "Found $f at '$path'"
# Note the same filename may be present farther down the PATH
# Once the first executable is found, exit
exit 0
fi
done
# Getting here means file was not found
echo "$f could not be found"
exit 1
Here are the results:
rbanikaz@lightsaber:~$ ./which.sh grep
Found grep at '/usr/bin/grep'
rbanikaz@lightsaber:~$ ./which.sh foo
foo could not be found
rbanikaz@lightsaber:~$