杂乱和重复的输出

时间:2015-09-18 18:36:00

标签: linux bash shell

我的代码在功能上是正确的。问题是输出不是应该的样子。事情应该正确间隔,出于某种原因,当我使用$ line变量时,我得到一个重复的文件名。

这是我的代码:

#!/bin/bash
 printf "Enter a directory path."
 read path
 if [ -e $path ]
    then
            echo -e "Filename \t Lines \t \t Type"
            echo -e "--------- \t ------ \t -----"
            for f in `$path/ls`
                    do
                            if [ -f $f ]
                                    then
                                    lines=`wc -l $f`
                                    echo -e " $f \t $lines \t \t Regular File "

                            else
                                    echo -e " $f \t N/A \t \t Directory File "



                            fi
                    done
    else
            printf "Directory path does not exist"
fi

输出如下:

Filename         Lines           Type 
---------        ------          -----
Desktop         N/A             Directory File
Documents       N/A             Directory File
Downloads       N/A             Directory File
Music   N/A             Directory File
mycrontab       0 mycrontab             Regular File
mycrontab.txt   1 mycrontab.txt                 Regular File
wc: mynewfile.txt: Permission denied
mynewfile.txt                   Regular File
myscript        26 myscript             Regular File
myscript.sh     24 myscript.sh                  Regular File
mytextlog.txt   91 mytextlog.txt                Regular File
Pictures        N/A             Directory File
Public          N/A             Directory File
Templates       N/A             Directory File
typescript      0 typescript            Regular File
Videos          N/A             Directory File
yumassignment.txt       1784 yumassignment.txt                  Regular File

1 个答案:

答案 0 :(得分:1)

您在评论中得到了答案。一些代码审查:

  • 你的缩进风格是......有趣。
  • 使用read -p "prompt" path,您不要单独打印提示
  • 始终引用变量,特别是如果值来自用户:if [ -e "$path" ]
  • don't parse ls outputfor f in "$path"/*
  • 如上所述:lines=$(wc -l < $"f")