shell 基本操作小结

时间:2022-08-05 12:00:32

1.echoif else fi命令

#!/bin/bash
echo hello;echo there
filename=demo.sh
if [ -e "$filename" ]; then
echo "$filename already exists!";cp $filename $filename.bak
else
echo "$filename does not exist!";
fi;
echo "File test complete!"

运行结果(demo.sh不存在):

hello
there
demo.sh does not exist!
File test complete!

需要注意的是filename=demo.sh等号两边是不能有空格的;if [ -e "$filename" ]中[]左右两侧都是有空格的。

2.shell基本操作

2.1 变量大于,等于,小于

#!/bin/bash
a=1
if [ $a -gt 0 ]; then
echo "greater than zero!"
else
echo "no more than zero!"
fi
if [[ $a -lt 0 ]]; then
echo "less than zero!"
else
echo "no less than zero!"
fi
if [[ a -eq 1 ]]; then
echo "equal to 1!"
else
echo "not equal to 1!"
fi

-gt表示大于;-lt表示小于;-eq表示等于。运行结果为:

greater than zero!
no less than zero!
equal to 1!

2.2 三目运算符(?