给定文件夹后,Shell脚本会打印出文件名 [英] Shell script print out file names when given a folder

查看:98
本文介绍了给定文件夹后,Shell脚本会打印出文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a shell script.. given a a folder as a command line arg it will print out the names of the files/folders in it

#!/bin/sh
folder="$1"
for f in "$folder"
do
  echo "$f"
done

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

This only prints out some the first file/folder of the given folder.

推荐答案

您需要在由目录分隔符/<分隔的 $ folder 之后的shell遍历运算符 * /code>:

You need shell globbing operator * after $folder separated by the directory separator /:

for f in "$folder"/*
do
  echo "$f"
done

* 将扩展到 $ folder 内的所有文件.

* would expand to all files inside $folder.

顺便说一句,我看到您使用了 sh (不是 bash )作为脚本解释器;在所有系统(例如在Ubuntu中)中, sh 都不是 bash ,因此,如果您要使用 bash (在这种情况下没有任何区别)但是),请在Shebang中显式使用 bash (例如#!/usr/bin/env bash ).

As an aside, i see you have used sh (not bash) as the script interpreter; sh is not bash in all systems (e.g. in Ubuntu), so if you were to use bash (does not make any difference in this case though), explicitly use bash in the Shebang (e.g. #!/usr/bin/env bash).

这篇关于给定文件夹后,Shell脚本会打印出文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆