1.if [ str1=str2 ];then fi ----当两个字符串相同时返回真
2.if [ str1!=str2 ];then fi ----当两个字符串不相等时返回真
3.if [ -n str1 ];then fi ----当字符串的长度大于0时返回真 (判断变量是否有值)
4.if [ -z str1 ];then fi ----当字符串的长度为0时返回真
1.int1 -eq int2 --相等
2.int1 -ne int2 --不相等
3.int1 -gt int2 --大于
4.int1 -ge int2 --大于等于
5.int1 -lt int2 --小于
6.int1 -le int2 --小于等于
1. -r file --用户可读为真
2. -w file --用户可写为真
3. -x file --用户可执行为真
4. -f file --文件存在且为正规文件为真
5. -d file --如果是存在目录为真
6. -c file --文件存在且为字符设备文件
7. -b file --文件存在且为块设备文件
8. -s file --文件大小为非0为真,可以判断文件是否为空
9. -e file --如果文件存在为真
1. -a --与
2. -o --或
3. ! --非
我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n 代表一个数字,1 为执行脚本的第一个参数,2 为执行脚本的第二个参数,以此类推……
以下实例我们向脚本传递三个参数,并分别输出,其中 $0 为执行的文件名:
#!/bin/bash
# author:菜鸟教程
# url:www.runoob.com
echo "Shell 传递参数实例!";
echo "执行的文件名:$0";
echo "第一个参数为:$1";
echo "第二个参数为:$2";
echo "第三个参数为:$3";
为脚本设置可执行权限,并执行脚本,输出结果如下所示:
$ chmod +x test.sh
$ ./test.sh 1 2 3
Shell 传递参数实例!
执行的文件名:./test.sh
第一个参数为:1
第二个参数为:2
第三个参数为:3
参数处理 | 说明 |
---|---|
$# | 传递到脚本的参数个数 |
$* | 以一个单字符串显示所有向脚本传递的参数。 如"$*"用「"」括起来的情况、以"$1 $2 … $n"的形式输出所有参数。 |
$$ | 脚本运行的当前进程ID号 |
$! | 后台运行的最后一个进程的ID号 |
$@ | 与$*相同,但是使用时加引号,并在引号中返回每个参数。 如"$@"用「"」括起来的情况、以"$1" "$2" … "$n" 的形式输出所有参数。 |
$- | 显示Shell使用的当前选项,与set命令功能相同。 |
$? | 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。 |
#!/bin/bash
# author:菜鸟教程
# url:www.runoob.com
echo "Shell 传递参数实例!";
echo "第一个参数为:$1";
echo "参数个数为:$#";
echo "传递的参数作为一个字符串显示:$*";
执行脚本,输出结果如下所示:
$ chmod +x test.sh
$ ./test.sh 1 2 3
Shell 传递参数实例!
第一个参数为:1
参数个数为:3
传递的参数作为一个字符串显示:1 2 3
#!/bin/bash
# author:菜鸟教程
# url:www.runoob.com
echo "-- \$* 演示 ---"
for i in "$*"; do
echo $i
done
echo "-- \$@ 演示 ---"
for i in "$@"; do
echo $i
done
执行脚本,输出结果如下所示:
$ chmod +x test.sh
$ ./test.sh 1 2 3
-- $* 演示 ---
1 2 3
-- $@ 演示 ---
1
2
3
代码:
file=”thisfile.txt”
echo “filename: ${file%.*}”
echo “extension: ${file##*.}”
输出:
filename: thisfile
extension: txt
s1="abcdefg"
s2="bcd"
result=$(echo $s1 | grep "${s2}")
if [[ "$result" != "" ]]
then
echo "$s1 include $s2"
else
echo "$1 not include $s2"
fi
~
fileName=/home/sss/data/hk
if [[ $fileName =~hk ]]
then
echo "$fileName include hk"
else
echo "not include"
fi
*
A="helloworld"
B="low"
if [[ $A == *$B* ]]
then
echo "包含"
else
echo "不包含"
fi