bash
这是本文档旧的修订版!
目录
bash 使用心得
复制文件夹中前N个文件
先 cd 进入该文件夹。 如果N=1000,命令如下:
ls |head -n 1000 |xargs -i cp -r {} /home/xuqiong/data/testimg/nosee/test
批量修改Java文件的包名
原来的包名是 com.xxx.utils,现在要改为 test。有 100 个这样的文件。 使用 sed 命令:
sed -i 's|com.xxx.utils|test|' *.java
查看磁盘信息
df -h
当前日期格式化
date +%Y-%m-%dT%H:%M:%S
相对路径转化为绝对路径
path=$(cd ../abc; pwd) echo $path
判断目录是否存在
path=~/codes
echo $path # 输出绝对路径
if [ -d "$path" ]; then
echo 'exist codes'
fi
if [ -d "/Users/plough/codes" ]; then
echo 'exist codes'
fi
# 相对路径是没用的
if [ ! -d "~/codes" ]; then
echo 'no exist codes'
fi
判断文件是否存在
path=~/codes/test.py
if [ -f "$path" ]; then
echo 'exist'
fi
获取当前脚本所在目录
dir=`dirname $0` script_dir=`readlink -f $dir/`
替换文本文件中的内容
sed -i "s#%name#Tom#g" hello.yml
文件夹中保留指定数量的文件
reserve_num=10;
((delete_num=$(ls /var/lib/logs|wc -l) - reserve_num));
if ((delete_num > 0)); then
rm -rf $(ls /var/lib/logs|sed \"s:^:/var/lib/logs/:\"|sort|head -n $delete_num);
fi;
查看一个目录中的文件大小
du -d 1 -h
获取本机 ip 地址
ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'
根据实际情况,可能存在多个 ip,还要再用 grep 过滤一下。
try/catch 异常处理
{ # try
command1 &&
#save your output
} || { # catch
# save log for exception
}
操作 bash 数组、字典
# Array pretending to be a Pythonic dictionary
ARRAY=( "cow:moo"
"dinosaur:roar"
"bird:chirp"
"bash:rock" )
for animal in "${ARRAY[@]}" ; do
KEY="${animal%%:*}"
VALUE="${animal##*:}"
printf "%s likes to %s.\n" "$KEY" "$VALUE"
done
printf "%s is an extinct animal which likes to %s\n" "${ARRAY[1]%%:*}" "${ARRAY[1]##*:}
字符串大小写转换
var="Hello,Word"
# 把变量中的第一个字符换成大写
echo ${var^}
# 把变量中的所有小写字母,全部替换为大写
echo ${var^^}
# 把变量中的第一个字符换成小写
echo ${var,}
# 把变量中的所有大写字母,全部替换为小写
echo ${var,,}
判断变量是否为空
#!/bin/bash
function is_empty() {
if [ -z "$1" ]; then
return 1
fi
return 0
}
function is_empty_ignore_space() {
if [ -z "${1// }" ]; then
return 1
fi
return 0
}
is_empty ''
echo $? # 1
is_empty_ignore_space ''
echo $? # 1
is_empty ' '
echo $? # 0
is_empty_ignore_space ' '
echo $? # 1
获取正在运行的 pod
kubectl get pods|tail -n +2|awk '{print $1}'
关闭正在运行的 k8s 服务
kubectl delete sts `kubectl get sts|tail -n +2|awk '{print $1}'`
kubectl delete deployment `kubectl get deployments|tail -n +2|awk '{print $1}'`
bash.1583896363.txt.gz · 最后更改: 2020/03/11 11:12 由 plough