提供されたファイルがあるかどうかを確認し、それ以外の場合はエラーメッセージを生成するスクリプトを作成できますか?次のコードがありますが、動作しません。
#!/bin/bash
echo "enter file name:"
read source
file= $source
if [ -f "$file" ] && find "$file" | grep -q .
then
echo "the file exists."
else
echo "the file does not exist."
fi
ベストアンサー1
&& findステートメントが何をしているのかわかりません。以下を試してください。
#!/bin/bash
read -p "enter file name: " source
file=$source
if [[ -f "$file" ]]; then
echo "the file exists."
else
echo "the file does not exist."
fi
編集する
file= $source
また、ちょうど機能しないスペースがあることがわかりました。そうする必要があるfile=$source
編集2
ファイルが現在のディレクトリにない場合に備えて、検索部分でファイルを検索する必要がありますか?この場合、次のようにすることができます。 (これは粗末なスクリプトであり、それを使用すべき妥当な理由は思いません。)
#!/bin/bash
read -p "enter file name: " source
file=$(find / -type f -name "$source" 2> /dev/null | head -n1)
if [[ -f "$file" ]]; then
echo "the file exists."
else
echo "the file does not exist."
fi