记录一些自己经常使用的shell语句,方便随时查看:
1)获取当前时间:
time = $(date "+%Y-%m-%d %H:%M:%S")
echo "time is &time"
2) if-then-else语句
if [ 1 -eq 1 ]
then
echo "hello world"
else
echo "goodbye world"
fi
或者
if [ 1 -eq 1 ]; then
echo "hello world"
elif
then
echo "goodbye world"
else
echo "see you"
fi
两种写法没有实质区别,但要注意在进行数值判断时,中括号两边需要加空格,否则会出错(之前忘记加空格,导致花费了超多时间排查问题)
3)判断文件夹(目录)是否存在:
if [ -d $filename ]; then
echo "$filename exists"
fi
#判断文件夹不存在时,则在-d前面加感叹号
if [ ! -d $filename ]; then
echo "$filename does not exist"
fi
判断文件是否存在:
if [ -f $file ]; then
echo "$file exists"
fi
#判断文件不存在时,则在-f前面加感叹号
if [ ! -f $file ]; then
echo "$file does not exist"
fi