I accidentally found a very interesting book of Shell programming, E, content is 101 shell case, stick to tomorrow to read a, write a little experience.
The following is an example 001:
#!/bin/sh # inpath-verifies That's a specified program are either valid as is, # or so it can be found in the PATH dire
Ctory list. In_path () {# Given a command and the path, try to find the command. Returns # 0 if found and executable, 1 if not.
This is the temporarily modifies # the IFS (input field separator) but restores it upon completion. cmd=$1 path=$2 retval=1 oldifs= $IFS ifs= ":" for directory into $path do if [-X $directory/$cmd]; Then Retval=0 # If we are here, we are found $cmd in $directory fi do ifs= $oldIFS return $retval} CHECKFORCMDINPA Th () {var=$1 # The variable slicing notation in the following conditional # needs some explanation: ${var#expr} retur NS Everything after # "match for ' expr '" in "Variable value (if any), and # ${var%expr} returns everything that Doe SN ' t match (in a # case, just the very-character.
You can also does this in # Bash with ${var:0:1}, and your 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: $ command" >&2; Exit 1 fi Checkforcmdinpath "$" case $?
In 0) echo "$ found in PATH";;
1) echo "found or not executable";;
2) echo "found in PATH";; ESAC Exit 0
The purpose of this script is to detect whether the input option is in path.
There are several areas of the script that deserve attention:
1 It uses the function nesting, nested the In_path function in the Checkforcmdinpath.
2 if ["${var%${var#?}}" = "/"] the ${var%${var# in this statement is the first character of the display variable, or it can be substituted with ${varname:1:1} or $ (echo $var | cut-c1).
3) Elif! In_path $var $PATH; Then this means that if the In_path $var $PATH execution is not 0,
Problem:
The input echo, Echo_err, and/etco_err all return the correct result, but the input/etc/echo_right (the presence of the executable file but not in path) returns found in path. I think the script still needs to be perfected.