1.if判断语句(判断是否为某一个字符):
read命令读入一个值:
read name
① 判断是否为 “first”或者"second":
if [ "x$name" == "xfirst" ]; then
echo "The input is first"
elif [ "x$name" == "xsecond" ]; then
echo "The input is second"
else
echo "The input isn't what we need"
fi
即只要有if就要有 ;和then,一个if语句以fi结尾。
之所以要加一个x是为了防止下面的错误:有时候使用判断语句,当我们输入为空的时候会报错
[: ==: unary operator expected
是因为为空的时候判断语句的左边就是什么都没有,当然就无法判断了。
②.判断输入中是否有空格
因为read是读取一行,当需要输入一个单词,就可以使用以下判断
if [ "${name/ /}" != "$name" ]; then
echo "the input isn't one word"
③判断大小,对于数字判断来说不能直接写:
[ $test < 10 ]
要写为:
[ $test -lt 10 ]
-lt是小于,-gt是大于, -ge是大于等于, -le小于或等于,-ne是不等于,-eq是等于。
l:less ; g:greater ;e: equal ; t: than ;
2. while循环
while [ "x$types" != "x" ]; do
循环的内容
done
3.for循环
files="txt1.txt tx2.txt tx3.txt"
for filename in $files; do
rm $filename
done
4.脚本判断中遇到的一些问题:
当我想使用以下命令判断文件是否存在时,会输入“not exist!”虽然在命令行中可以cd到这个目录,但是在脚本中无法这样判断,将其改为绝对路径才可以:
if [ -d "~/cpfer/vmware" ]; then
echo "the file is exist! "
else
echo "not exist!"
fi
将 ~替换为${HOME}
即可
4.一些常用命令:
获取当前脚本的路径:
project_path=$(cd `dirname $0`; pwd)
批量替换$newpath 路径下以.txt为文件后缀的文件中的内容,将first替换为second:
vmname="first"
newname="second"
sed -i "s/$vmname/$newname/g" `find $newpath -name "*.txt"`