#!/bin/bash str="a b c d e f g h i j" echo "the source string is "${str} #源字符串 echo "the string length is "${#str} #字符串长度 echo "the 6th to last string is "${str:5} #截取从第五个后面开始到最后的字符 echo "the 6th to 8th string is "${str:5:2} #截取从第五个后面开始的2个字符 echo "after delete shortest string of start is "${str#a*f} #从开头删除a到f的字符 echo "after delete widest string of start is "${str##a*} #从开头删除a以后的字符 echo "after delete shortest string of end is "${str%f*c} #从结尾删除f到c的字符 echo "after delete widest string of end is "${str%%*c} #从结尾删c前面的所有字符包括c
然后我们执行一下,看一些这个截取规则:
forlinx@forlinx:~$ bash shell_test.sh the source string is a b c d e f g h i j a b c the string length is 25 这个长度是包括空格的 the 6th to last string is d e f g h i j a b c the 6th to 8th string is d after delete shortest string of start is d e f g h i j a b c可以看到a到c这个只截取了一次 after delete widest string of start is after delete shortest string of end is a b c d e after delete widest string of end is
三、shell中的判断式
Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。
针对数值:
参数
说明
-eq
等于则为真
-ne
不等于则为真
-gt
大于则为真
-ge
大于等于则为真
-lt
小于则为真
-le
小于等于则为真
比如
num1=100 num2=100 if test $[num1] -eq $[num2] then echo '两个数相等!' else echo '两个数不相等!' fi
针对字符串:
参数
说明
=
等于则为真
!=
不相等则为真
-z 字符串
字符串的长度为零则为真
-n 字符串
字符串的长度不为零则为真
num1="ru1noob" num2="runoob" if test $num1 = $num2 then echo '两个字符串相等!' else echo '两个字符串不相等!' fi
针对文件:
参数
说明
-e 文件名
如果文件存在则为真
-r 文件名
如果文件存在且可读则为真
-w 文件名
如果文件存在且可写则为真
-x 文件名
如果文件存在且可执行则为真
-s 文件名
如果文件存在且至少有一个字符则为真
-d 文件名
如果文件存在且为目录则为真
-f 文件名
如果文件存在且为普通文件则为真
-c 文件名
如果文件存在且为字符型特殊文件则为真
-b 文件名
如果文件存在且为块特殊文件则为真
用于判断的命令:&&和||
&&后面的是当前面为真时执行,||前面命令执行为假时执行
这里以test命令为例,也可以和其他命令搭配
echo "Please input a filename: " read filename test -f $filename && echo "the file is ordinary file" || echo "the file is not ordinary file" test -d $filename && echo "the file is document folder" || echo "the file is not document folder" test -r $filename && echo "the file can read" || echo "the file can not read" test -w $filename && echo "the file can write" || echo "the file can not write" test -x $filename && echo "the file can executable" || echo "the file can not executable"
测试:
forlinx@forlinx:~$ touch test forlinx@forlinx:~$ bash shell_test.sh Please input a filename: test the file is ordinary file the file is not document folder the file can read the file can write the file can not executable
四、shell条件分支结构语句
单分支:
if 条件;then 结果 fi
双分支:
if 条件;then 结果1 else 结果2 fi
多分支:
if 条件1;then 结果1 elif条件2;then 结果2 ..... else 结果n fi