Linux shell用户变量中存在差异

Linux shell用户变量中存在差异,linux,bash,shell,Linux,Bash,Shell,问题:脚本将接收任意数量的文件名作为参数。脚本应该检查提供的每个参数是文件还是目录。如果目录报告。如果是文件,则应报告文件名加上其中存在的行数 下面是我的代码 #!/bin/sh for i in $*; do if [ -f $i ] ; then c=`wc -l $i` echo $i is a file and has $c line\(s\). elif [ -d $i ] ; then echo $i is a directory

问题:脚本将接收任意数量的文件名作为参数。脚本应该检查提供的每个参数是文件还是目录。如果目录报告。如果是文件,则应报告文件名加上其中存在的行数

下面是我的代码

#!/bin/sh
for i in $*; do
    if [ -f $i ] ; then
       c=`wc -l $i`
       echo $i is a file and has $c line\(s\). 
    elif [ -d $i ] ; then
    echo $i is a directory. 
    fi
done
输出:

shree@ubuntu:~/unixstuff/shells$ ./s317i file1 file2 s317h s317idir
file1 is a file and has 1 file1 line(s).
file2 is a file and has 2 file2 line(s).
s317h is a file and has 14 s317h line(s).

我的问题是:每次迭代时,变量c的值是1 file1、2 file2、14 s317h。而我希望它是1,2和14。为什么它包含前一个值而不包含后一个值?我错在哪里

注意:s317i是我的文件名,file1 file2 s317h和s317idir是命令行参数


敬请告知。

这是
wc
命令的输出。例如:

$ wc -l file1
1 file1
但是,如果您从
file1
重定向
stdin
,或将另一个命令的
stdout
导入
wc
,则它不会给出文件名

$ wc -l < file1
1
$ cat file1 | wc -l
1
$wc-l
因此,您的脚本应如下所示:

#!/bin/bash

for arg in $@; do
    if [ -f $arg ]; then
        echo $arg is a file and has `wc -l < $arg` lines.
    elif [ -d $arg ]; then
        echo $arg is not a file, it is a directory.
    fi
done
#/bin/bash
对于$@中的arg;做
如果[-f$arg];然后
echo$arg是一个文件,有'wc-l<$arg'行。
elif[-d$arg];然后
echo$arg不是一个文件,它是一个目录。
fi
完成

请注意,我使用的是
bash
而不是
sh
$@
而不是
$*

“为什么它包含前面的值”-只要试着在控制台上键入
wc-l一些_文件
,您就会明白为什么。我想这不是你想问的问题。试着
c=`cat$I | wc-l`
,这样wc就没有文件名可以打印。有一点:如果你使用“test”外部或他的fork“[”而不是“[[”内部KSH/Bash指令,你必须用双引号保护你的变量。请参阅以获取更多详细信息。