1.test命令
test主要是起到了测试作用,用于查看文件是否存在,权限等信息,主要是数值,字符,文件三方面进行测试。
&&和||命令例如:#!/bin/bash
echo "please input file name"
read -p "filename"filename
test -e $filename && echo "file exist" || echo "file no exist"
#!/bin/bash
echo "please input two str"
read -p "frist str"friststr
read -p "second str"secondstr
test $friststr==$secondstr && echo "friststr==secondstr"|| echo "friststr!=seconder"
中括号和[]
可以用来做判断符号,注意符号内部字符串应该加入“”号,要不会报错
默认变量:
$0和$n表示shell脚本参数,shell脚本本身命令为$0
$#表示脚本的最后一个编号,
$@表示$1$2等,表示所有的参数
例子:#!/bin/bash
echo "file name"$0
echo "total param name "$#
echo "whole param "$@
echo "first param"$1
echo "second param"$2
这个脚本可以运行,输入a b时,输出
file namemy.sh
total param name2
whole param a b
first parama
second paramb
2.shell脚本条件判断,函数与循环
条件判断:if条件判断:then
//判断成立要做的事情
fi
代码例子:#!/bin/bash
read -p echo"please input (y/n)"valus
if [ "$valus" == "Y" ]||[ "$valus" == "y" ]; then
echo "your input is y"
exit 0
fi
if[ "$valus" == "N" ]||[ "$valus" == "n" ];then
echo "your input is n"
exit 0
fi
这个脚本就可以进行判断,注意!!!:在这个脚本中用正点原子代码会出现找不到指令的现象,这个现象是因为代码不规范,现在版本的应该注意加入空格,在[]中两边应该有空格,在“==”两边也应该使用空格隔开,在then 前面也应该使用空格隔开,注意我写的代码这个就有空格隔开,注意这一点。
if else的用法:if else 语句的else后面不能跟条件 可以通过修改上面的代码体现出来
#!/bin/bash
read -p echo"please input (y/n)"valus
if [ "$valus" == "Y" ]||[ "$valus" == "y" ]; then
echo "your input is y"
exit 0
else
echo "your input is n"
exit 0
fi
使用else if命令例子如下:
#!/bin/bash
read -p echo"please input (y/n)"valus
if [ "$valus" == "Y" ]||[ "$valus" == "y" ]; then
echo "your input is y"
exit 0
elif [ "$valus" == "N" ]||[ "$valus" == "n" ]; then
echo "your input is n"
exit 0
else
echo "your input can not identfy"
fi
千万要注意空格的使用,在c语言中空格可能没有这么重要,但是在shell脚本命令中空格属于语法的一种
case语句的用法:
case$变量 in
“第一个变量内容”)
程序段
;; //表示该程序段结束
“第二个变量内容”)
程序段
;;
"第n个程序段内容")
程序段
;;
esac
例子:
case $1 in
"a")
echo "param is a"
;;
"b")
echo "param is b"
;;
*)
echo "input can not identify"
;;
esac
注意通配符*不可以加双引号.
3.shell脚本函数
shell脚本函数也支持函数,函数写法如下:function fname(){
//代码段
}
#!/bin/bash
function help(){
echo "this help cmd!"
}
function close(){
echo "this is close help"
}
case $1 in
"h")
help
;;
"c")
close
;;
esac
这个就是代码段
4.shell循环
while 循环 例子:while [ "$valus" == "close" ]
do
read -p "please input str:"valus
done
echo "stop"
for循环 例子:#!/bin/bash
for name in zzk1 zzk2 zzk3
do
echo "your name is $name "
done
\ #!/bin/bash
read -p "please input count :" count
total=0
for((i=0; i<=count; i=i+1))
do
total=$(($total+$i))
done
echo "1+2+...........+$count=$total"
这些就是我的今天全部的笔记,今天我发现遇到的很多问题是因为空格的原因,这种的空格一定要重点排查,明天就国庆啦,放假快乐,我是不会放弃成为嵌入式高手的。