2016-11-22 33 views
0

我想創建一個程序,列出shell bash中給定目錄中的文件,子文件夾和軟鏈接的數量。 程序應該具備先決條件並將它們用作輸入。所以1美元就是你想要列出內容的目錄。 它也應該能夠只顯示文件或僅使用 -f(用於文件)軟鏈接,-l(用於軟鏈接)和-d(指定的目錄內的目錄)使用shell以特定的方式列出目錄的內容

好吧,這是我來了到目前爲止。

#!/bin/bash 

function funk { 

for i in $1; do 

     counttotal=$(find "$i" -maxdepth 1 -printf .   |wc -c); 
     countdir=$(find "$i" -maxdepth 1 -type d -printf .  |wc -c); 
     countfile=$(find "$i" -maxdepth 1 -type f -printf .  |wc -c); 
     countlink=$(find "$i" -maxdepth 1 -type l -printf .  |wc -c); 
     echo " : $i [Total:$counttotal] [Dir:$countdir | Files:$countfile | Links:$countlink]" 
     done 
} 

function justfile { 

for i in $1; do 
     countfile=$(find "$i" -maxdepth 1 -type f -printf .  |wc -c); 
     echo " : $i [ Filer:$countfile ]" 
done 
} 

function justdir { 
for i in $1; do 
     countdir=$(find "$i" -maxdepth 1 -type d -printf .  |wc -c); 
     echo " : $i [ Dir:$countdir ]" 
done 
} 

function justlink { 
for i in $1; do 
     countlink=$(find "$i" -maxdepth 1 -type l -printf .  |wc -c); 
     echo " : $i [ Links:$countlink ]" 
done 

} 

現在我有低於此if語句,將檢查是否$ 1什麼,然後會在工作目錄中運行臨陣脫逃。然後它會檢查$ 1是否是-f,如果是,它將運行唯一文件。否則它只會在你給它的目錄中運行。

但是我現在看到的,這是這樣做的非常低效的方法將意味着我將不得不至少有5 if語句在一個...

我一直在四處尋找一種方式做到這一點,偶然發現'shift',它似乎是這樣做的方式...

但我很不確定如何去使用它,並會非常感謝一些幫助。

+1

你應該在這裏用的是[getopts的(http://wiki.bash-hackers.org/howto/getopts_tutorial ) – Mansuro

回答

0

至於建議您可以使用getopts或者可以使用以下的bash純解:

echo Usage : script.sh -f file <or> script.sh -d dir 
while [[ $# -gt 0 ]]; do 
    key="$1" 
    case "$key" in 
     -f|--file) 
     shift 
     ARG_FILE="$1" 
     ;; 
     -d|--dir) 
     shift 
     ARG_DIR=1 
     ;; 
     *) 
     FLAG_CURRENT_DIRECTORY=1 
     ;; 
    esac 
    # Shift after checking all the cases to get the next option 
    shift 
done 

# Process further based on the options 
相關問題