【问题标题】:Show the content of a file by its name按名称显示文件的内容
【发布时间】:2019-06-26 15:26:10
【问题描述】:

我正在尝试构建一个脚本,要求用户输入文件名,一旦编写完成,它就会完全显示该文件中的内容。


例如

假设我有一个位于 /home/evaluation/ 的目录,其中包含多个文件:

在/home/evaluation/file01

Lorem ipsum dolor sit amet.

在/home/evaluation/file02

Lorem ipsum sit amet.

在/home/evaluation/file03

Lorem ipsum dolor

我期待构建一个脚本,它会要求我写文件名,我想读,一旦这个文件写完,它就会显示它的所有内容。

所以如果我输入:file01,它会显示给我:

Lorem ipsum dolor sit amet.

否则,如果目录中不存在文件,则写成:“no file found”。

【问题讨论】:

  • 您觉得有什么理由需要遍历目录吗?似乎您只想 cat 文件(如果存在)或打印消息(如果不存在)。我错过了什么吗?
  • 你说得对,我不需要任何循环。

标签: bash shell scripting


【解决方案1】:

试试这个,看看你是否得到了你想要的东西

#!/bin/bash
echo Enter file name  # ask for the file name
read fileName  # get the a file name from the user and store it in fileName
if [ ! -f $fileName ] ; then  # check to see if the file exists
   echo "File not found"  # print a message if it does not
   exit  # all done so exit 
fi
# cat the file if we are still here , ie the file exists
cat $fileName  

if [] 在 bash 中定义了一个 test 所以 -f file_name 检查文件是否存在并且是常规文件 所以[ ! -f $fileName ]如果文件不存在就为真,那么就打印消息,否则打印内容

【讨论】:

  • 非常感谢!我用循环做错了。
猜你喜欢
  • 2014-05-06
  • 2015-12-18
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 2013-09-21
相关资源
最近更新 更多