shell脚本编写一些基础但容易忘记的小技巧(持续更新)

判断变量是否为空

1.变量通过引号引起来

#!/bin/bash
para1=
if [ ! -n "$para1" ]; then
    echo "para1 is NULL"
else
    echo "para1 is not NULL"
fi
2.直接通过变量判断

#!/bin/bash
para1=
if [ ! $para1 ]; then
    echo "para1 is NULL"
else
    echo "para1 is not NULL"
fi
3.使用test判断

#!/bin/sh
dmin=
if test -z "$dmin"
then
	echo "dmin is not set"
else
	echo "dmin is set !"
fi
4.使用""判断

#!/bin/sh
dmin=
if [ "$dmin" = "" ]
then
	echo "dmin is not set"
else
	echo "dmin is set !"
fi

判断有这个目录并删掉这个目录

[ -d /tmp/gos ] && rm -fr /tmp/gos


shell统计一列数值的总和

catflow.log.20170419|grepVPN201606130004|awk'{print$7}'|awk'{sum+=$1}END{printsum}'


shell按条件抽取文件内容

catflow.log.20170419|grepVPN201606130004|awk'{FS=""}{if($2>=1492615740&&$2<=1492616880)print$0}'


date +%s 可以得到UNIX的时间戳;
用shell将时间字符串与时间戳互转:
date -d "2010-10-18 00:00:00" +%s 输出形如:1287331200
而时间戳转换为字符串可以这样做:
date -d @1287331200 "+%Y-%m-%d" 输出形如:2010-10-18
如果需要得到指定日期的前后几天,可以:
1、seconds=`date -d "2010-10-18 00:00:00" +%s` #得到时间戳
2、seconds_new=`expr $seconds + 86400` #加上一天的秒数86400
3、date_new=`date -d @$seconds_new "+%Y-%m-%d"` #获得指定日前加上一天的日前
时间戳转换--2010-10-18 00:00:00这种格式
date -d "1970-01-01 UTC 1287331200 seconds" "+%F %T"


shell双重条件
if["$TimeStamp">="$start_time"-a"$TimeStamp"<="$end_time"]


获取shell脚本所在绝对路径
baseDirForScriptSelf=$(cd"$(dirname"$0")";pwd)

循环读取文件并执行
cat$file_name|awk'NR>1'|whilereadheadtail
do
headip=`./switchINT.sh$head`
tailip=`./switchINT.sh$tail`
echo"headIP:$headip">>./IP.txt
echo"tailIP:$tailip">>./IP.txt
done

shell脚本执行cp直接覆盖不提示

alias cp="cp -f"

直接输入以上命令,在当前shell生效。放入 ~/.bashrc 中,以后的新shell中都生效(当前shell不生效,退出再重新login以后生效)

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...