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
获取当前脚本所在目录
set -ex 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]##*:}
bash.1582857405.txt.gz · 最后更改: 2022/12/28 17:53 (外部编辑)