Shell 脚本在给定文件夹时打印出文件名

Dar*_*ers 3 bash shell scripting

我正在编写一个 shell 脚本.. 给定一个文件夹作为命令行参数,它将打印出其中的文件/文件夹的名称

#!/bin/sh
folder="$1"
for f in "$folder"
do
  echo "$f"
done
Run Code Online (Sandbox Code Playgroud)

这只会打印出给定文件夹的第一个文件/文件夹。

hee*_*ayl 5

由目录分隔符分隔*后,您需要 shell globbing 运算$folder/

for f in "$folder"/*
do
  echo "$f"
done
Run Code Online (Sandbox Code Playgroud)

*将扩展到$folder.

顺便说一句,我看到您使用sh(not bash) 作为脚本解释器;sh并非bash在所有系统中(例如在 Ubuntu 中),因此如果您要使用bash(尽管在这种情况下没有任何区别),请bash在 Shebang 中明确使用(例如#!/usr/bin/env bash)。