当前位置:网站首页>Shell script combat (2nd edition) / People's Posts and Telecommunications Press Script 1 Find programs in the PATH

Shell script combat (2nd edition) / People's Posts and Telecommunications Press Script 1 Find programs in the PATH

2022-08-09 10:29:00 Mary Soda Meatloaf

#!/bin/bash#inpathin_path(){cmd=$1 ourpath=$2 result=1 #1oldIFS=$IFS IFS=":" #2for directory in $ourpathdoif [ -x $directory/$cmd ]; then #3result=0fidoneIFS=$oldIFSreturn $result}checkForCmdInpath(){var=$1if [ "$var" != "" ];thenif [ "${var:0:1}" = "/" ];then #4if [ ! -x $var ];thenreturn 1fielif ! in_path $var "$PATH";thenreturn 2;fifi}checkForCmdInpath "$1"case $? in0) echo "$1 found in PATH" ;;1) echo "$1 not found or not executable" ;;2) echo "$1 not found in PATH" ;;esacexit 0

1:Default variables for shell scripts

$# is the number of arguments passed to the script
$0 is the name of the script itself
$1 is the first argument passed to the shell script
$2 is the second argument passed to the shell scriptparameters
[email protected] is a list of all parameters passed to the script
$* is a single string showing all parameters passed to the script, unlike positional variables, the parameters can be more than 9
$$is the current process ID number of the script running
$? is the exit status of the last command, 0 means no error, other means there is an error

sh test.sh opt1 opt2 opt3 opt4$0 $1 $2 $3 $4

2:IFS separator

https://zhuanlan.zhihu.com/p/36513249

3: Judgment symbol [ ]

Each component in

'[ ]' needs to be separated by spaces.Variables are best surrounded by quotes.

Check file permissions

-r Whether the file exists, and the readable permission
Whether the -w file exists, and the writable permission
Whether the -x file exists, and the executable permission
Whether the -u file exists, and hasSUID attribute
-g Whether the file exists and has the SGID attribute
Whether the file exists and has the Sticky bit attribute
-s Whether the file exists and is a non-blank file

4: Variable segmentation syntax, starting from the offset, truncating according to the given length (if no length is provided, the rest of the string will be returned)

Script 1 running result

原网站

版权声明
本文为[Mary Soda Meatloaf]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091026200356.html