2011-03-23 68 views
1

我必須編寫一個shell腳本來獲取目錄名稱作爲參數,然後將目錄中文件的名稱和大小列出到文本文件中。我對Linux有一點了解,所以你能幫我嗎?Linux Shell腳本:將目錄的內容列入文件

所有我設法寫的是這樣的:

for entry in "$search_dir"/* 
do 
    if [ -f "$entry" ];then 
    echo "$entry" 
    fi 
done 

輸出文件應該是這樣的:

filename1 filesize1 
filename2 filesize2 

我對取得的目錄名作爲參數問題

回答

1

像這個:

#! /bin/bash 
if [ $# -gt 0 ] ; then 
    ls $1 > textfile.txt 
else 
    echo "Please provide Foldername"; 
fi 

此外,您可以檢查是否$ 1文件夾,但這應該足以

+0

感謝sharpner,就像一個魅力。怎麼打印文件大小? – Jim 2011-03-23 16:37:52

+0

ls -la或-ls -lach不管你看起來不錯 – sharpner 2011-03-23 16:38:42

+0

對不起,但我不明白。如果[$#-gt 0];然後 ls $ 1> textfile.txt ls -la不能按我想要的方式工作。我想有filename1 size1(在第一行)filename2 size2(在第二行)等...對不起,所有的麻煩 – Jim 2011-03-23 16:44:51

2

你可以很容易地把一個腳本的輸出到使用文件>

例如

ls /tmp > ./contentsOfDir.txt 

將傾將ls命令放入當前目錄中的contentsOfDir.txt中。

該腳本可能看起來像這樣的是bash shell:

#!/bin/bash 
ls -l $1 > contentsOfDir.txt 

,被稱爲

./myScript dirNameToBeDumpedInFile 

看一看this bash scripting tutorial,它涵蓋了基礎知識。

0
#!/bin/sh 

if [ ! -d "$1" ]; then 
    echo "usage: $0 <directory>"; 
    exit 1; 
fi 

cd $1; 
find -maxdepth 1 -type f -print0 | xargs -0 -n1 du -h; 
cd -; 

這將輸出類似:

4.0K ./bundle.h 
24K ./walker.o 
4.4M ./git-show 
4.0K ./sha1-lookup.h 
100K ./refs.o 
2

如果你要打印的文件夾內容的一個漂亮的樹和它的子文件夾,您可以使用「樹」。

如果這不是你的系統上安裝,你必須這樣做第一:

sudo apt-get install tree 

那麼語法是非常簡單的。如果你想輸出保存到一個文件:

tree -h -A path/to/dir > output.txt 
  • -A用於確保輸出使用ASCII字符。
  • -h將以人們可讀的格式打印每個文件大小。

您有更多的選擇來限制輸出,您可以通過使用「--help」選項得到:

> tree --help 
    -a   All files are listed. 
    -d   List directories only. 
    -l   Follow symbolic links like directories. 
    -f   Print the full path prefix for each file. 
    -L level  Descend only level directories deep. 
    -o filename Output to file instead of stdout. 
    -s   Print the size in bytes of each file. 
    -h   Print the size in a more human readable way. 
    --dirsfirst List directories before files (-U disables).