shell脚本时不时就要用到,但是一些常用的片段却没有记住,这里整理一个笔记
CUR_DIR="$(dirname $0)"
基本每个脚本都要用到,否则脚本执行的时候就容易受到当前目录的影响,可能出现执行结果不一致
if condition; then
commands;
elif condition; then
commands;
fi
date +%Y%m%d%H%M%S
# 纪元秒,方便用来实现简单的计时
date +%s
start=$(date +%s)
sleep 2
end=$(date +%s)
echo $[ end - start ]
function getTiming(){
start=$1
end=$2
start_s=`echo $start| cut -d '.' -f 1`
start_ns=`echo $start| cut -d '.' -f 2`
end_s=`echo $end| cut -d '.' -f 1`
end_ns=`echo $end| cut -d '.' -f 2`
time_micro=$(( (10#$end_s-10#$start_s)*1000000 + (10#$end_ns/1000 - 10#$start_ns/1000) ))
time_ms=`expr $time_micro/1000 | bc `
echo "$time_micro microseconds"
echo "$time_ms ms"
}
begin_time=`date +%s.%N`
sleep 1
end_time=`date +%s.%N`
getTiming $begin_time $end_time
if [ -f $file ]; then
echo "$file exists"
else
echo "$file does not exists"
f
if [ -d $dir ]; then
echo "$dir exists"
else
echo "$dir does not exists"
fi
appIds=(1 2 3 4 5 100)
for appId in ${appIds[@]}
do
echo "${appId}"
done
length=${#fileArray[@]}
if [ ! -n "$1" ]; then
echo "need one parameter"
else
echo "parameter is $1"
fi
let newNum=$num+100
rm -rf all-808{1..9}.log
#生成连续IP地址
'%s,' 192.168.58.{1..255}
#!/usr/bin/env bash
func(){}
来定义函数,而不是func{}
[[]]
来代替[]
$()
将命令的结果赋给变量,而不是反引号printf
代替echo
进行回显shellcheck
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有