从shell脚本中提取文件名,该脚本创建带有日期后缀的文件

时间:2012-02-21 15:23:42

标签: shell terminal backup

我的常规备份工作命令:

 ditto -c -k --sequesterRsrc --keepParent ~/Library/'Application Support/MyProg'/ ~/Dropbox/'Application Support/MyProg'/`date "+MP_backup_%Y-%m-%d_%H%M%S"`.zip

这会创建一个不错的文件: MP_backup_2012-02-21_133445.zip 。但我想构建这个脚本并在完成时提供一个很好的咆哮通知。我如何提取生成的文件名并提供一个很好的咆哮通知,例如“备份成功完成。备份到MP_backup_2012-02-21_133445.zip”

我的代码/伪代码是这样的:

 ## Set the Backup path ##
 BKP="~/Dropbox/Application Support/MyProg"

 ## Set KM Source path ##
 SRC="~/Library/Application\ Support/MyProg/"

 # Creat a zipped bkup with dated suffix
 ditto -c -k --sequesterRsrc --keepParent "$SRC" "$BAK/`date "+MP_backup_%Y-%m-%d_%H%M%S"`.zip

 ## Growl a message saying the the File name is successfully created, if created else throw error ##

 if [ <backup created> ] 
  then
    growl/echo "Backup succesfully complete. Backed up at MP_backup_2012-02-21_133445.zip"
  else 
    echo "Me no find Backup FAIL!"
   fi 

非常感谢将上述伪代码转换为美丽光荣的工作代码的指导。

干杯。

感谢窥视,所有提供的答案的信息都用于提出以下最终工作解决方案:

## Set the Backup path ##
bkp="Dropbox/Application Support/My Prog"

## Set KM Source path ##
src="Library/Application Support/My Prog"

## Preferred Date Suffix ##
filename=$(date +"MP_backup_%Y-%m-%d_%H%M%S.zip")

# Creat a zipped bkup with dated suffix
ditto -c -k --sequesterRsrc --keepParent ~/"$src"/ ~/"$bkp"/"$filename"

## Growl the File name is successfully created ##
if [ -f ~/"$bkp"/"$filename" ]
  then
    echo "Backup successfully complete. Backed up at ~/$bkp/$filename";
  else 
    echo "Me no find Backup FAIL!";
fi 

3 个答案:

答案 0 :(得分:1)

只需将date调用移动到变量,然后重复使用它:

# Create a zipped bkup with dated suffix
BACKUPFILE=`date "+MP_backup_%Y-%m-%d_%H%M%S"`
ditto -c -k --sequesterRsrc --keepParent "$SRC" "$BAK/$BACKUPFILE.zip

(...)

growl/echo "Backup succesfully complete. Backed up at $BACKUPFILE"

答案 1 :(得分:1)

单独生成文件名并将其存储在变量中,以便您可以在其他地方使用该变量:

filename="$BAK/`date "+MP_backup_%Y-%m-%d_%H%M%S"`.zip
ditto -c -k --sequesterRsrc --keepParent "$SRC" "$filename"

...

growl/echo "Backup succesfully complete. Backed up at $filename"

答案 2 :(得分:1)

也许:

## Set the Backup path ##
 BKP="~/Dropbox/Application Support/MyProg"

 ## Set KM Source path ##
  SRC="~/Library/Application\ Support/MyProg/"

DATE=`date +"%Y-%m-%d_%H%M%S"`

 # Creat a zipped bkup with dated suffix
 ditto -c -k --sequesterRsrc --keepParent "$SRC" "$BAK/MP_backup_$DATE.zip

 ## Growl a message saying the the File name is successfully created, if created else throw error ##

 if [ <backup created> ] 
      then
growl/echo "Backup succesfully complete. Backed up at MP_backup_$DATE.zip"
  else 
    echo "Me no find Backup FAIL!"
    fi