Whether the shell script in PATH can be used to detect the entered option $1
It is believed that many inexperienced people are at a loss about whether the shell script in PATH can be used to detect the input option $1. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Here is an example 001:
#! / bin/sh# inpath-Verifies that a specified program is either valid as is,# or that it can be found in the PATH directory list.in_path () {# Given a command and the PATH, try to find the command. Returns # 0 if found and executable, 1 if not. Note that this temporarily modifies # the IFS (input field separator) but restores it upon completion. Cmd=$1 path=$2 retval=1 oldIFS=$IFS IFS= ":" for directory in $path do if [- x $directory/$cmd]; then retval=0 # if we're here, we found $cmd in $directory fi done IFS=$oldIFS return $retval} checkForCmdInPath () {var=$1 # The variable slicing notation in the following conditional # needs some explanation: ${var#expr} returns everything after # the match for 'expr' in the variable value (if any), and # ${var%expr} returns everything that doesn't match (in this # case, just the very first character. You can also do this in # Bash with ${var:0:1}, and you could use cut too: cut-C1. If ["$var"! = "]; then if [" ${var%$ {var#?}} "=" / "]; 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 command" > & 2; exit 1ficheckForCmdInPath "$1" case $? In 0) echo "$1 found in PATH"; 1) echo "$1 not found or not executable"; 2) echo "$1 not found in PATH";; esacexit 0
The purpose of this script is to detect whether the entered option $1 is in PATH.
There are several things to note about this script:
1) it uses function nesting and in_path function nesting in checkForCmdInPath.
2) ${var%$ {var#?}} in the statement if ["${var%$ {var#?}}" = "/"] is the first character that displays the variable, or you can replace it with ${varname:1:1} or $(echo $var | cut-C1).
3) elif! In_path $var $PATH; then means that if the execution result of in_path $var $PATH is not zero, then
Question:
It is found that the input echo, echo_err, / etco_err all return the correct result, but the input / etc/echo_right (there is an execution file but is not in the PATH) returns found in PATH. I think this script still needs to be improved.
After reading the above, do you know whether the shell script in PATH can be used to detect the entered option $1? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!