Determine whether the string is included in the shell script, and determine whether the file or folder exists

1、字段 grep:
案例: 
str1="abcdefgh"
str2="def"
result=$(echo $str1 | grep "${str2}")
if [[ "$result" != "" ]];then
    echo "包含"
else
    echo "不包含"
fi

2. 字符串运算符 =~:
案例:
str1="abcdefgh"
str2="def"
if [[ $str1 =~ $str2 ]];then
    echo "包含"
else
    echo "不包含"
fi

3、 正则表达式中的通配符 *:
案例: 
str1="abcdefgh"
str2="def"
if [[ $str1 == *$str2* ]];then
    echo "包含"
else
    echo "不包含"
fi
 

Reference:
https://www.cnblogs.com/smlile-you-me/p/11425404.html

The method of judging whether the file and directory exist in the linux shell
-e filename is true if the filename exists

-d filename is true if filename is a directory

-f filename is true if filename is a regular file

-L filename is true if filename is a symbolic link

-r filename is true if filename is readable

-w filename is true if filename is writable

-x filename is true if filename is executable

-s filename is true if the file length is not 0

-h filename is true if the file is a soft link

#!/bin/sh
#判断文件存在,判断是否为文件夹等
testPath="/Volumes/MacBookProHD/Mr.Wen/08 shell命令"
testFile="/Volumes/MacBookProHD/Mr.Wen/08 shell命令/fileWen"
#判断文件夹是否存在 -d
if [[ ! -d "$testPath" ]]; then
 echo "文件夹不存在"
else
 echo "文件夹存在"
fi
#判断文件夹是否存在,并且具有可执行权限
if [[ ! -x "$testFile" ]]; then
 echo "文件不存在并且没有可执行权限"
else
 echo "文件存在并有可执行权限"
fi
#判断文件是否存在
if [[ ! -f "$testFile" ]]; then
echo "文件不存在"
else
 echo "文件存在"
 fi

Reference: https://www.jb51.net/article/186273.htm

Guess you like

Origin blog.csdn.net/weixin_44695793/article/details/108699305