ユーザー生成変数を外部コマンドに渡してみてください。

ユーザー生成変数を外部コマンドに渡してみてください。

ユーザー入力を要求し、その変数をfindコマンドに渡すbashスクリプトがあります。私が知っている方法で変数を引用/エスケープしてみましたが、いつも失敗します。

read -p "Please enter the directory # to check: " MYDIR
count=`/usr/bin/find /path/to/$MYDIR -name *.txt -mmin -60 | wc -l`
if [ $count != 0 ]
    then 
         echo "There have been $count txt files created in $MYDIR in the last hour"
    else 
         echo "There have been no txt files created in the last hour in $MYDIR "
    fi

実行すると、次の結果が表示されます。

Please enter the directory # to check: temp_dir

/usr/bin/find: paths must precede expression
Usage: /usr/bin/find [-H] [-L] [-P] [path...] [expression]
There have been no txt files created in the last hour in temp_dir 

ベストアンサー1

-nameオプションでパターンを引用する必要があります。

count="$(/usr/bin/find /path/to/$MYDIR -name '*.txt' -mmin -60 | wc -l)"

引用符を使用しない場合、シェルはパターンを拡張します。あなたのコマンドは次のとおりです

/usr/bin/find "/path/to/$MYDIR" -name file1.txt file2.txt ... -mmin -60 | wc -l

.txt名前が to オプションで終わるすべてのファイルを提供します-name。これにより構文エラーが発生します。

おすすめ記事