条件が失敗した場合、エラーをどのようにリダイレクトしますか? [閉じる]

条件が失敗した場合、エラーをどのようにリダイレクトしますか? [閉じる]

私はSTDERRとループの初期テスト段階で2>をいつ/どこに配置するかをよりよく理解しようとしています。

私のスクリプトは次のとおりです...

#!/bin/bash

file1=/tmp/file1
file2=/tmp/file2

if [ -e $file1 -o -e $file2 ]; then
  if ls $file1 2>> err.log ; then
     echo "file1 exists" | tee -a job.log
  fi

  if ls $file2 2>> err.log ; then
    echo "file2 exists" | tee -a job.log
  fi
else
 echo "neither $file1 or $file2 exists"
fi

しかし、file1またはfile2が存在しない場合は、err.logに以下を追加したいと思います。

ls: /tmp/file1 にアクセスできません: そのファイルまたはディレクトリがありません

しかし、err.logには何も記録されません。何を見逃しているのかよくわかりませんが、論理は簡単だと思います。

どんな洞察力でも高く評価されます。

ベストアンサー1

CASが指摘したように、.を不必要に使用していますls。スクリプトは次のように書くことができます。

#!/bin/bash

file1='/tmp/file1'
file2='/tmp/file2'

if [[ -e "$file1" ]]; then
    echo "file1 exists" | tee -a job.log
else
    echo 'ls: cannot access /tmp/file1: No such file or directory' >>err.log
fi
if [[ -e "$file2" ]]; then
    echo "file2 exists" | tee -a job.log
else
    echo 'ls: cannot access /tmp/file2: No such file or directory' >>err.log
fi
[[ ! -e "$file1" && ! -e "$file2" ]] && echo "neither $file1 or $file2 exists"

lsエラーはおそらく変更する必要がありますが、これがエラーファイルで見たいものなので、そのままにしておきます。 :)

おすすめ記事