顯示具有 tar 標籤的文章。 顯示所有文章
顯示具有 tar 標籤的文章。 顯示所有文章

2010年8月9日

[shell script] 驗證 tar 解壓縮的執行結果

前陣子在用 tar 解壓縮更新程式的時候,發現某個檔案沒有被正確被覆蓋,經過確認,tar 指令的確有用到 -m 參數 (用法參考:這篇),難道是 tar 這個全世界用了 N 年的工具出了問題?

雖然最後證實那個檔案是因為其他的原因被還原到舊版,但是在那段真相水落石出之前的空窗期我寫了一個短短的 script 來驗證 tar 的執行結果,完整程式碼如下:

#!/bin/bash
#created by Tim, verify the tar unzip operation is successful
#this file should be put in the /tmp directory

#read the log file from the output of "tar -zxvfm XXX.tar.gz > /tmp/tar.log" command

BASEDIR=`pwd`  cd /tmp
files=`cat tar.log`
count=0

for file in $files
do
   #check the last modified date of each file, it should be the same
   ls -l "$BASEDIR/$file" 
   count=`expr $count + 1`
done
echo "count: $count"

#verify files count
#precondition: there should be only 1 .tar.gz file in the /tmp directory
#the number of files in the .tar.gz file
tarCount=`tar -tv -f *.tar.gz | wc -l`   
echo "tarCount: $tarCount"

if [ $count -eq $tarCount ]; then

   echo "file count check OK!"
else
   echo "file count check FAILED!!"
fi 

程式很單純,只是先利用 tar 的 -v (verbose) 參數把執行過程中解壓縮的
檔案相對路徑紀錄到 /tmp 下的 tar.log 檔,而後逐一比對 log 檔中的
路徑與目前系統中實際的檔案修改時間是否相同,最後會比較 tar 檔中
所含的檔案數量與 tar.log 檔中紀錄到的檔案數量是否一致。 
 
雖然這程式應該沒啥用 (tar 出問題的機率超低),但還是擺著備忘一下,
當作 shell script 的範本也好 :p 

2010年3月26日

讓 tar 檔解壓縮出來的檔案的 modification time 變成執行解壓縮指令的當下時間 (用於以解壓縮 tar 檔的方式更新程式時)

嗯 … 標題有點囉嗦,在系統上要更新程式時,常常會先將欲更新的程式,重點在於在下指令解壓縮 tar 檔時,如果只用一般常見的下法:tar zxvf xxx.tar.gz 的話,那麼解壓縮出來的檔案的 modification time 會維持當初打包 tar 檔的時間,而不會是執行解壓縮 tar 檔的時間,在資安稽核要求很嚴謹的環境中,以上的狀況是不被接受的。

要讓 tar 檔解壓縮出來的檔案的 modification time 被修正為執行指令的當下時間很簡單,參考 tar 指令的 man page

-m, --touch, --modification-time

don't extract file modified time

此處渴看到關鍵字「touch」,再查一下 touch 指令的 man page

touch [OPTION]... FILE...

Description

Update the access and modification times of each FILE to the current time.

所以說,爾後解壓縮 tar 檔時只要下如此的指令:tar zxvfm xxx.tar.gz,那麼解壓縮出來的檔案的 modification time 就會是執行指令的當下時間啦!(看起來是 tar 這支程式會自動幫你 touch 壓縮檔內的所有檔案/目錄)

PS. 昨天為了這個需求,還寫了個 4、50 行的 Perl 程式 (先建立 temp 目錄 –> 把原始 tar 檔複製到 temp 目錄 –> 在 temp 目錄解壓縮 –> 把解壓縮出來的所有檔案/目錄 touch 一遍 –> 再壓縮成一個新的 tar 檔 –> 把新的 tar 檔複製到真正的目的資料夾 –> 在目的資料夾解壓縮 –> 回頭刪掉 temp 目錄),現在看起來真的是蠢斃了 =.= 幸好隔了一天就發現 -m 這個參數 … 可見認真的讀完 man page 是多麼重要的事情!

不過在寫 Perl 的過程中又多學到了一些處理檔案、目錄的技巧,例如 mkdir -p 可以自動幫你建立完整的目錄階層;cp -a 類似沒有加上 -m 的 tar,效果等同於幫指定目錄建立另一個名稱不同的目錄,再把指定目錄下的所有子目錄和檔案複製到新目錄中,但是新目錄下的檔案 modification time 跟原目錄是一樣的 …

Google Spreadsheet 裡用規則運算式

最近因為工作關係,遇到要用 Google Form 及 Google Sheet 所以研究了 Google Sheet 裡的一些 function 怎麼用 首先,分享一下如何在 Google Sheet 裡用規則運算 :D