如何创建一个脚本来检查提供的文件是否存在,如果不存在则创建错误消息。我有以下代码,但它不起作用:
#!/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
Run Code Online (Sandbox Code Playgroud)
I'm not sure what your && find statement is doing...try like this:
#!/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
Run Code Online (Sandbox Code Playgroud)
Edit
Also I just noticed you had a space in file= $source
that will not work. It needs to be file=$source
Edit 2
I'm guessing that find part was supposed to search for the file in case it wasn't in the current directory? In which case you can do something like this (This is a sloppy script and I can't think of a good reason to use it):
#!/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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6565 次 |
最近记录: |