繁体   English   中英

Linux:检查文件是否为某文件[-f不起作用]

[英]Linux : check if something is a file [ -f not working ]

我当前正在尝试列出目录中所有文件的大小,该目录作为脚本的第一个参数传递,但是Linux中的-f选项不起作用,或者我丢失了什么。

这是代码:

for tmp in "$1/*"
do
  echo $tmp
  if [ -f "$tmp" ]
     then num=`ls -l $tmp | cut -d " " -f5`
       echo $num
  fi
done

我该如何解决这个问题?

我认为错误是由于您的glob语法在单引号或双引号中均无效,

for tmp in "$1"/*; do
..

进行上述操作以将引号之外的内容扩展开。

您的脚本可能还有几处改进,

  1. 用双引号括住变量以防止单词分裂,例如echo "$temp"
  2. 反引号命令替换``是具有多个问题的旧式语法,请使用$(..)语法。

linux中的[-f“ filename”]条件检查用于检查文件的存在,它是常规文件。 供参考,请以本文为参考,

    -b FILE
          FILE exists and is block special

   -c FILE
          FILE exists and is character special

   -d FILE
          FILE exists and is a directory

   -e FILE
          FILE exists

   -f FILE
          FILE exists and is a regular file

   -g FILE
          FILE exists and is set-group-ID

   -G FILE
          FILE exists and is owned by the effective group ID

我建议您尝试使用[-e“ filename”]并查看它是否有效。 干杯!

至少在命令行上,这段脚本可以做到这一点:

for tmp in *; do echo $tmp; if [ -f $tmp ]; then num=$(ls -l $tmp | sed -e 's/  */ /g' | cut -d ' ' -f5); echo $num; fi; done;

如果cut使用空格作为定界符,则会在每个空格符号处进行削减。 有时,列之间有多个空格,并且计数很容易出错。 我猜想在您的情况下,您只是碰巧echo了一个空格,看上去好像什么都没有。 使用sed命令,我删除了多余的空格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM