【问题标题】:Shell script looping directory [duplicate]Shell脚本循环目录[重复]
【发布时间】:2021-02-08 17:58:47
【问题描述】:

我想编写一个 shell 脚本,它将遍历目录中的所有文件并执行echo "put ${filename}"。 如何为这个逻辑使用 while 循环。

【问题讨论】:

  • 逐步分解并尝试一次找出一个(它们都已经在 StackOverflow 和许多其他资源上得到了回答):1)我如何从 shell 获取文件名列表迅速的? 2)如何从脚本中使用此列表并将其存储到变量中? 3) 在这样的列表上循环的语法是什么?
  • 是的,我可以得到 1 和 2 的结果。但是,对于循环列表,我们如何使用 while 循环。(通常,我们可以使用 for 循环)。我在管道中使用这个 while 逻辑。将单个文件输入管道正在工作。但是用目录文件做这件事,就不行了。
  • echo ${LIST} | while read filename; do echo "put ${filename}"; done${LIST} 每行包含一个文件名。
  • 文件名=*.sh; i=0;arr=();对于 $filename 中的文件;do arr[i]=$files; (( i++ ));完毕; index=0;while [ $index -lt $i ] do echo "${arr[$index]}";(( index++ ));完成

标签: shell while-loop


【解决方案1】:

您可以使用 find 命令获取目录中所有文件的列表,并使用圆括号将其转换为数组。最后循环遍历数组并打印出来。

path=some_path
files=( $(find $path -maxdepth 1 -type f) )

for file in "${files[@]}"; do
do
  echo "put $file"
done

【讨论】:

  • 这个逻辑可以用while吗?
猜你喜欢
  • 2013-10-06
  • 2021-08-21
  • 1970-01-01
  • 2015-04-02
  • 2017-04-09
  • 2013-04-03
  • 2015-04-10
  • 2017-11-13
  • 1970-01-01
相关资源
最近更新 更多