条件でエラーが発生した場合

条件でエラーが発生した場合

Bashコーディングでは、line3はxyz/symlinks_paths.txtから取得したパスです。

while read -r line3
do
    if [[ $(ls -lh $line3 | grep zzz.exe | grep '[8-9][0-9][0-9][MG]') -ne 0 ]] 
    then 
        echo $line3 >> xyz/size_list.txt
        exit 1
    fi
done < xyz/symlinks_paths.txt

スクリプトで次のエラーが発生します。 (h.sh はスクリプト名です.)

h.sh: line 20: [[: -r--r--r-- 1 syncmgr GX 838M Dec  1 21:55 zzz.txt: syntax error in expression (error token is "r--r-- 1 syncmgr GX 838M Dec  1 21:55 zzz.txt")

ベストアンサー1

ここでの問題は、解析を試みていることですlsいつも悪い考えです。バラよりなぜ`ls`を解析しないのですか?なぜこれが起こるのか説明してください。

ファイルサイズが必要なstat場合

minsize=$(( 800 * 1024 * 1024 ))

# alternatively, if you have `numfmt` from GNU coreutils, delete the line above
# and uncomment the following line:
#minsize=$(echo 800M | numfmt --from=iec)

while read -r line3 ; do
  if [ "$(stat -L --printf '%s' "$line3")" -gt "$minsize" ]; then
    echo "$line3" >>  xyz/size_list.txt
  fi
done < xyz/symlinks_paths.txt

注:ファイル名を入力すると、リストされたファイル名がシンボリックリンクである可能性が高いため、上記のstat-L(別名)」オプションを使用しました。--dereferenceそれ以外の場合は、-Lシンボリックstatリンクに従わずにシンボリックリンク自体のサイズを印刷します。


ファイル名とともにファイルサイズを出力ファイルに印刷する場合、ループは次のようwhileになります。

while read -r line3 ; do
  fsize=$(stat -L --printf '%s' "$line3")

  if [ "$fsize" -gt "$minsize" ]; then
    fsize=$(echo "$fsize" | numfmt --to=iec)
    printf "%s\t%s\n" "$fsize" "$line3" >>  xyz/size_list.txt
  fi
done < xyz/symlinks_paths.txt

おすすめ記事