簡體   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