You need to implement a shell command checking utility that verifies whether a given command is accessible and executable based on its presence in the system's PATH or if it is provided as an absolute path. The utility should check if the command exists and is executable, then provide appropriate messaging based on these checks.
Functionality to Build
Implement a function that checks:
If the command is an absolute path and exists as an executable.
If the command is not absolute, it checks if the command is present in the current user's PATH and is executable from those directories.
The utility should handle input arguments and return appropriate exit statuses based on the checks performed.
Ensure that if the command is found in the PATH, output "found in PATH"; if not found or not executable, output "not found or not executable"; if not found in the PATH, output "not found in PATH".
Expected Inputs and Outputs
Input: A single command string as a command-line argument.
Output:
If the command is found and executable, print: "<command> found in PATH"
If the command is an absolute path but not executable, print: "<command> not found or not executable"
If the command is not found in the PATH, print: "<command> not found in PATH"
File Location and Naming
The solution should be implemented in a file named cmd_checker.sh located at /app/.
Ensure that this file has executable permissions.
Tests
The following test script will be used to verify your solution:
bash
#!/bin/bash
in_path()
{
cmd=$1
ourpath=$2
result=1
oldIFS=$IFS
IFS=":"
for d in $ourpath; do
if [ -x $d/$cmd ]; then
result=0
fi
done
IFS=$oldIFS
return $result
}
check_cmd()
{
var=$1
if [ "$var" != "" ]; then
if [ "${var:0:1}" = "/" ]; then
if [ ! -x $var ]; then
return 1
fi
elif ! in_path $var "$PATH"; then
return 2
fi
fi
}
if [ $# -ne 1 ]; then
echo "usage: $0 cmmand" >&2
exit 1
fi
check_cmd "$1"
case $? in
0 ) echo "$1 found in PATH" ;;
1 ) echo "$1 not found or not executable" ;;
2 ) echo "$1 not found in PATH" ;;
esac
exit 0