shell脚本:备份文件

1.备份文件
#!/usr/bin/env bash

date=$(date "+%Y%m%d")
file_path="/root/zy/test/bak/bak.txt"
if [[ -f ${file_path}.${date} ]];then
    num=$(ls -l $file_path.${date}*| wc -l)
    cp $file_path ${file_path}.${date}_${num}
else
    cp $file_path ${file_path}.${date}
fi

  

2.备份文件(写成函数)

#!/usr/bin/env bash
bak(){
  date=$(date "+%Y%m%d")
  file_path=$1
  if [[ -f ${file_path}.${date} ]];then
      num=$(ls -l $file_path.${date}*| wc -l)
      cp $file_path ${file_path}.${date}_${num}
  else
      cp $file_path ${file_path}.${date}
  fi
}

# 使用函数
bak json.json

  

3.备份文件(备份某个文件,加上使用方法提示)

#!/usr/bin/env bash
# 错误使用参数,则提示 if [ "$#" -ne 1 ]; then echo -e "\033[32mUsage:\n\t$0 <filepath>\033[0m" echo -e "for example:\n\t $0 log.log" echo -e "\t $0 /root/log.log" exit 1 fi date=$(date "+%Y%m%d") file_path=$1 if [[ -f ${file_path}.${date} ]];then num=$(ls -l $file_path.${date}*| wc -l) cp $file_path ${file_path}.${date}_${num} else cp $file_path ${file_path}.${date} fi

  

posted @ 2024-12-14 21:52  铿锵有力自信且坚定  阅读(50)  评论(0)    收藏  举报