2013-10-28 77 views
1

我想寫一個簡單的bash腳本來顯示文件的內容。Bash腳本,'for'循環的用法

#!/bin/bash 

echo 'Input the path of a file or directory...' 
read File 

if [ -e $File ] && [ -f $File ] && [ -r $File ] 
    then 
    echo 'Displaying the contents of the file '$File 
    cat $File 


elif [ -d $File ] && [ -r $File ] 
then 
echo 'Displaying the contents of the directory '$File  
    for FILE in `ls -R $File` 
     do 
       cd $File/$FILE 
       echo 'Displaying the contents of the file '$FILE 
       cat $FILE 
     done 

else 
echo 'Oops... Cannot read file or directory !' 
fi 

用戶應輸入文件或目錄路徑。如果用戶輸入文件,則程序使用cat顯示該文件。如果用戶輸入一個目錄,它應該顯示所有文件的內容,包括子目錄中的文件。該計劃的這一部分工作不好。我想得到一個結果,不會顯示錯誤,如「沒有這樣的文件或目錄」,但只有文件的內容。你可以幫我嗎 ? 在此先感謝。

+1

切勿在'$(command)'中使用'for i'。請參閱此答案以獲取更多詳細信息:http://stackoverflow.com/questions/19606864/ffmpeg-in-a-bash-pipe/19607361#19607361 否則,我認爲最好的解決方案是使用'find'來描述在這個線程的一些答案。 –

回答

6

ls -R是找到所有子目錄中的所有文件的錯誤的工具。 find是一個更好的選擇:

echo "displaying all files under $File" 
find "$File" -type f -printf "Displaying contents of %p\n" -exec cat {} \; 
+0

感謝您的回覆!代碼工作正常,但有沒有辦法在顯示文件內容之前打印文件的名稱? – buster

+0

'... -exec echo {}; cat {} \;' – chepner

+0

謝謝chepner,但是我找到'':找不到'-exec'''的參數。 – buster

3

您可以打印在當前目錄中的所有文件只是做

for f in * do 
    cat $f; 
done 
+0

'cat *'會做同樣的事情(錯誤)。 – jlliagre

+0

是的,但在for循環中,他可以輕鬆地添加其他命令(如「調試」回顯)。我剛給他的結構。爲什麼錯了? – LeartS

+0

你是正確的循環允許更多的靈活性。主要問題是'for'循環是錯誤的方法。 OP使用'ls -R',這清楚地表示子目錄是預期的。他的循環和你的都不妥善處理這種情況。 「發現」是要走的路。 – jlliagre

2

find命令會爲您節省大量的邏輯:

#!/bin/bash 

echo 'Input the path of a file or directory...' 
read File 
DirName="." 

if echo $File | grep '/' ; then 
    DirName=$(dirname $File) 
    File=$(basename $File) 
fi 

find "$DirName" -type f -name "$File" -exec cat {} \; 
find "$DirName" -type d -name "$File" -exec ls {} 

先找會尋找所有「常規」(型的F)文件名$文件和貓他們 第二個發現將查找所有'目錄'(-type d)並列出它們。

如果他們沒有找到,那麼-exec部分將不會執行。 grep將拆分路徑,在那裏是斜線。

+0

感謝您的迴應!當我嘗試運行你的腳本時,我得到一個錯誤''find:warning:Unix文件名通常不包含斜線......''。 – buster

+0

爲了解決這個問題,您可以使用基本名稱和dirname來分隔名稱,例如找到$(dirname $ File)-name「$(basename $ File)」 – SilverCode