我需要根据用户输入查找文件名,然后读出该文件,但这仅适用于目录中的第一个文件,不适用于其他文件,请帮忙!
这是到目前为止我的 .sh 文件
#!/bin/bash
dir="test_users"
echo "Please enter filename"
read filename
find . -name "$filename"
cat $filename
if [ "$?" -ne 0 ]
then
echo "file: $filename does not exist"
fi
答案1
cat
如果您对无法读取文件时的错误消息感到满意,则脚本非常简单:
#!/bin/bash
printf "Please enter filename: "
read -r filename
cat "$filename"
如果您想在无法读取文件时输出自己的错误消息,您可以这样做:
#!/bin/bash
printf "Please enter filename: "
read -r filename
if [ -r "$filename" ]; then
# File is readable, so print contents
cat "$filename"
elif [ -f "$filename" ]; then
# File exists, but file cannot be read
echo "Cannot read file $filename."
else
# File does not exist
echo "File $filename does not exist."
fi