####Date: 2018.7.2
1、参考:shell基础知识:
https://blog.csdn.net/a343315623/article/details/51436889
https://blog.csdn.net/babyfish13/article/details/52981110
https://blog.csdn.net/babyfish13/article/details/52981110
https://jingyan.baidu.com/article/72ee561a6e0d60e16138dfde.html
find: https://www.cnblogs.com/lanchang/p/6597372.html
https://www.cnblogs.com/nzbbody/p/4391802.html
https://www.cnblogs.com/ariclee/p/6137456.html
2、shell中for循环的几种格式
格式一:语法循环形式
#!/bin/bash
for((i=1;i<=10;i++));
do
echo $(expr $i * 3 + 1);
end
格式二:seq序列形式
#!/bin/bash
`for i in $(seq 1 10)
do
echo $(expr $i * 3 + 1);
done
格式三:执行命令后进行循环
#!/bin/bash
for i in `ls`;
do
echo $i is file name! ;
done
格式四:find查找循环,一般速度比较慢
for i in `find . -type f -name "*.sh"`
do
haha=`echo "$i" | awk -F/ '{print $2}'`
echo $haha
done
注释:循环当前目录下的所有shell脚本,以/为分隔符,打印第二个字段。
格式五:列表形式
for i in 1 2 3 4 5
do
echo $i
done
3、shell下提取文件名和目录名
${}用于字符串的读取,提取和替换功能,可以使用${} 提取字符串
1、提取文件名
[root@localhost log]# var=/dir1/dir2/file.txt
[root@localhost log]# echo ${var##*/}
file.txt
2、提取后缀
[root@localhost log]# echo ${var##*.}
txt
3、提取不带后缀的文件名,分两步
[root@localhost log]# tmp=${var##*/}
[root@localhost log]# echo $tmp
file.txt
[root@localhost log]# echo ${tmp%.*}
file
4、提取目录
[root@localhost log]# echo ${var%/*}
/dir1/dir2
使用文件目录的专有命令basename和dirname
1、提取文件名,注意:basename是一个命令,使用{}
[root@localhost log]# echo $(basename $var)
file.txt
2、提取不带后缀的文件名
[root@localhost log]# echo $(basename $var .txt)
file
3、提取目录
[root@localhost log]# dirname $var
/dir1/dir2
[root@localhost log]# echo $(dirname $var)
/dir1/dir2
updated at 2018.9.19
4、shell中的字符串比较
- if [ str1 == str2 ] or if[ str1 = str2] 当两个串有相同内容、长度时为真
- if [ str1 != str2 ] 当串str1和str2不等时为真
- if [ -n str1 ] 当串的长度大于0时为真(串非空)
- if [ -z str1 ] 当串的长度为0时为真(空串)
- if [ str1 ] 当串str1为非空时为真
shell 中利用 -n 来判定字符串非空。
特别注意:
if [ -n ${var} ]
then
echo "var is $var"
fi
分析:var值为空的时候,不加双引号“ ”,不是我们想象中的不会执行,而是执行了,为什么呢?
通过分析可知:不加引号的情况下,var值为空时,${var}就是空,因此if[ -n ${var}]就变成了if [ -n ],等效于第五种用法if[ str1 ],因此判断为True,执行内部语句。
正确的应该是:
if [ -n "${var}" ]
then
echo "var is $var"
fi
参考自:
https://blog.csdn.net/u012883674/article/details/78650558
THE END!