简体   繁体   English

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

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

I am currently trying to list the size of all files in a directory which is passed as the first argument to the script, but the -f option in Linux is not working, or am I missing something. 我当前正在尝试列出目录中所有文件的大小,该目录作为脚本的第一个参数传递,但是Linux中的-f选项不起作用,或者我丢失了什么。

Here is the code : 这是代码:

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

How would I fix this problem? 我该如何解决这个问题?

I think the error is with your glob syntax which doesn't work in either single- or double-quotes, 我认为错误是由于您的glob语法在单引号或双引号中均无效,

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

Do the above to expand the glob outside the quotes. 进行上述操作以将引号之外的内容扩展开。

There are couple more improvements possible in your script, 您的脚本可能还有几处改进,

  1. Double-quote your variables to prevent from word-splitting, eg echo "$temp" 用双引号括住变量以防止单词分裂,例如echo "$temp"
  2. Backtick command substitution `` is legacy syntax with several issues, use the $(..) syntax. 反引号命令替换``是具有多个问题的旧式语法,请使用$(..)语法。

The [-f "filename"] condition check in linux is for checking the existence of a file and it is a regular file. linux中的[-f“ filename”]条件检查用于检查文件的存在,它是常规文件。 For reference, use this text as reference, 供参考,请以本文为参考,

    -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

I suggest you try with [-e "filename"] and see if it works. 我建议您尝试使用[-e“ filename”]并查看它是否有效。 Cheers! 干杯!

At least on the command line, this piece of script does it: 至少在命令行上,这段脚本可以做到这一点:

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;

If cut uses space as delimiter, it cuts at every space sign. 如果cut使用空格作为定界符,则会在每个空格符号处进行削减。 Sometimes you have more than one space between columns and the count can easily go wrong. 有时,列之间有多个空格,并且计数很容易出错。 I'm guessing that in your case you just happened to echo a space, which looks like nothing. 我猜想在您的情况下,您只是碰巧echo了一个空格,看上去好像什么都没有。 With the sed command I remove extra spaces. 使用sed命令,我删除了多余的空格。

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

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