简体   繁体   中英

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.

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,

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"
  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. 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. 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. 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. With the sed command I remove extra spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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