2011-05-16 74 views
1

我試圖使用convert命令將大量的pdf文件轉換爲圖像。我從我的文件夾中讀取所有文件,其中包含pdf和html文件,但html文件的擴展名爲「.pdf」。我從遠程服務器收到這些文件,所以我無法檢查哪些文件是pdf文件,哪些不是。我用這個代碼:通過ruby捕獲shell腳本執行日誌

%x[convert "#{source_path}" "#{destination_path}".jpg] 

source_path指向一個HTML文件,將返回以下錯誤:

GPL Ghostscript 8.60: Unrecoverable error, exit code 1 convert: Postscript delegate failed /home/20100.pdf': @ error/pdf.c/ReadPDFImage/645. convert: missing an image filename /home/test/20100-1.jpg' @ error/convert.c/ConvertImageCommand/2970. Success Error: /syntaxerror in -file- Operand stack:

Execution stack: %interp_exit
.runexec2 --nostringval--
--nostringval-- --nostringval-- 2 %stopped_push --nostringval--
--nostringval-- --nostringval-- false 1 %stopped_push 1889 1
3 %oparray_pop 1888 1 3
%oparray_pop 1872 1 3
%oparray_pop 1755 1 3
%oparray_pop --nostringval--
%errorexec_pop .runexec2
--nostringval-- --nostringval-- --nostringval-- 2 %stopped_push Dictionary stack:
--dict:1149/1684(ro)(G)-- --dict:0/20(G)-- --dict:70/200(L)-- Current allocation mode is local Current file position is 1

是否有可能得到任何布爾值,或者是有什麼辦法可以識別shell腳本是否正確執行?

回答

3

是,檢查是否$?.exitstatus爲0

>> %x{ls /etc/services} 
=> "/etc/services\n" 
>> $?.exitstatus 
=> 0 

>> %x{ls failfail} 
ls: cannot access failfail: No such file or directory 
=> "" 
>> $?.exitstatus 
=> 2 
3

除了tokland的解決方案,你也可以使用system,如果你不需要的命令的返回值(但只有當它工作正常):

>> system 'ls /etc/services' 
/etc/services 
=> true 
>> system 'ls /etc/failfail' 
ls: cannot access /etc/failfail: No such file or directory 
=> false 
1

這應該只將PDF文件轉換爲jpg。 (新文件將具有擴展名file.pdf.jpg)

ls -1 | xargs file | grep ': PDF document,' | sed 's/:.*//' | xargs -I % convert % %.jpg 

或這隻會PDF文件

ls -1 | xargs file | grep ': PDF document,' | sed 's/:.*//' | while read file; do b=`basename $file .pdf`; convert $file $b.jpg; done 
+0

感謝轉換成filename.jpg @ jm666。我喜歡第二個。這是完美的。而且,還有一件事,你可以根據我的意願改變第二個。我想用文件名和基本目錄重命名文件($ b.jpg)。例如,「/home/test/m.pdf」意味着我需要「jpg」,「test_m.jpg」的名稱。請幫幫我。 – 2011-05-17 05:07:01