文件系统浏览脚本

ShellShellBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在这个挑战中,你将创建一个简单的文件系统浏览脚本,展示你对 shell 脚本中基本文件和目录操作的理解。你将使用文件测试来检查文件和目录的存在性、类型和权限。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("Linux")) -.-> linux/BasicSystemCommandsGroup(["Basic System Commands"]) shell(("Shell")) -.-> shell/VariableHandlingGroup(["Variable Handling"]) shell(("Shell")) -.-> shell/ControlFlowGroup(["Control Flow"]) shell(("Shell")) -.-> shell/FunctionsandScopeGroup(["Functions and Scope"]) linux/BasicSystemCommandsGroup -.-> linux/echo("Text Display") linux/BasicSystemCommandsGroup -.-> linux/test("Condition Testing") shell/VariableHandlingGroup -.-> shell/variables_usage("Variable Usage") shell/ControlFlowGroup -.-> shell/if_else("If-Else Statements") shell/ControlFlowGroup -.-> shell/cond_expr("Conditional Expressions") shell/FunctionsandScopeGroup -.-> shell/func_def("Function Definition") subgraph Lab Skills linux/echo -.-> lab-388898{{"文件系统浏览脚本"}} linux/test -.-> lab-388898{{"文件系统浏览脚本"}} shell/variables_usage -.-> lab-388898{{"文件系统浏览脚本"}} shell/if_else -.-> lab-388898{{"文件系统浏览脚本"}} shell/cond_expr -.-> lab-388898{{"文件系统浏览脚本"}} shell/func_def -.-> lab-388898{{"文件系统浏览脚本"}} end

创建文件系统浏览脚本

任务

  1. 导航到 ~/project 目录,你会找到一个名为 file_explorer.sh 的部分完成的脚本。
  2. 打开 file_explorer.sh 文件并完成 check_item 函数,以浏览文件系统项。

要求

  • 脚本 file_explorer.sh 已经创建在 ~/project 目录中,并具有基本结构。
  • 你的任务是完成 check_item 函数:
    • 它应该接受一个参数(文件或目录的名称)。
    • 它应该执行以下检查并输出结果:
      • 如果该项存在
      • 如果它是文件还是目录
      • 如果它是可读的
    • 对每个检查使用适当的文件测试操作符(-e-f-d-r)。
  • 脚本的主要部分(调用函数的部分)已经提供。

示例

以下是完成后的脚本应如何工作的示例:

$ ./file_explorer.sh test_file.txt
Checking: test_file.txt
Exists: Yes
Type: File
Readable: Yes

$ ./file_explorer.sh non_existent.txt
Checking: non_existent.txt
Exists: No

$ ./file_explorer.sh test_directory
Checking: test_directory
Exists: Yes
Type: Directory
Readable: Yes
✨ 查看解决方案并练习

总结

在这个挑战中,你使用 shell 脚本创建了一个简单的文件系统浏览脚本。你练习了使用文件测试操作符来检查文件和目录的存在性、类型和权限。这个练习巩固了你对 shell 脚本中基本文件系统操作的理解,展示了文件与目录管理任务的实际应用。