shell脚本时不时就要用到,但是一些常用的片段却没有记住,这里整理一个笔记
CUR_DIR="$(dirname $0)"基本每个脚本都要用到,否则脚本执行的时候就容易受到当前目录的影响,可能出现执行结果不一致
if condition; then
commands;
elif condition; then
commands;
fidate +%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_timeif [ -f $file ]; then
echo "$file exists"
else
echo "$file does not exists"
fif [ -d $dir ]; then
echo "$dir exists"
else
echo "$dir does not exists"
fiappIds=(1 2 3 4 5 100)
for appId in ${appIds[@]}
do
echo "${appId}"
donelength=${#fileArray[@]}if [ ! -n "$1" ]; then
echo "need one parameter"
else
echo "parameter is $1"
filet newNum=$num+100rm -rf all-808{1..9}.log
#生成连续IP地址
'%s,' 192.168.58.{1..255}#!/usr/bin/env bash func(){}来定义函数,而不是func{} [[]]来代替[] $()将命令的结果赋给变量,而不是反引号printf代替echo进行回显shellcheck