简体   繁体   English

如何循环遍历某个目录中的所有文件(递归)

[英]How to loop through all files (recursively) in a certain directory

My task is to loop through all files (recursively) in a certain directory.我的任务是循环遍历某个目录中的所有文件(递归)。 The directory path is specified in the first parameter of the program.目录路径在程序的第一个参数中指定。 Now I have the following one-liner:现在我有以下一行:

find * -type f -exec echo "put {}" \;

, but I don't know how to specify directory path as the first parameter and how left * if there are no parameters. ,但我不知道如何将目录路径指定为第一个参数,如果没有参数,如何离开*。

If I'm doing it like:如果我这样做:

$YOUR_DIR = "*";
find "$YOUR_DIR" -type f -exec echo "put {}" \;

it isn't working.它不工作。

Please, help me.请帮我。

Parameters to a script are identified numerically as ${1} , ${2} , etc. (or $1 , $2 , etc.).脚本的参数在数字上标识为${1}${2}等(或$1$2等)。 You can also refer to ALL parameters using ${*} (or $* ).您还可以使用${*} (或$* )引用所有参数。 But you are using * , without the preceding dollar sign.但是您使用的是* ,前面没有美元符号。 This has a completely different meaning.这具有完全不同的含义。 It means 'all entries in the current directory'.它的意思是“当前目录中的所有条目”。

You should really just be using one directory, so check the first parameter, and make sure it is a directory before using it:你真的应该只使用一个目录,所以检查第一个参数,并确保它是一个目录,然后再使用它:

#!/bin/bash

if [ ! -d "${1}" ]; then
  echo "'${1}' is not a directory."
  exit 1
fi

find "${1}" -type f -exec echo "put {}" \;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何递归遍历目录以删除具有某些扩展名的文件 - How to loop through a directory recursively to delete files with certain extensions bash:处理(递归地)目录中的所有文件 - bash: processing (recursively) through all files in a directory 循环浏览目录中的所有文件? - Loop through all files in a directory? 递归删除所有文件,每个目录中除特定数目的文件 - Recursively delete all files except a certain number in each directory 如何递归删除目录中所有文件中的插入符号(^)字符? - How to recursively remove the caret (^) character recursively in all files in a directory? 使用bash:如何找到一种方法来搜索目录中的所有文件(递归?) - Using bash: how do you find a way to search through all your files in a directory (recursively?) 循环播放bash中目录中具有特定名称的所有文件 - Loop for all files with certain name in directory in bash 如何告诉ffmpeg依次遍历目录中的所有文件 - How to tell ffmpeg to loop through all files in directory in order 如何遍历bash给定目录中指定类型的所有文件? - How to loop through all files of a specified type in a given directory in bash? 如何在不使用 find 命令的情况下递归遍历文件并在 bash 中添加从某个文件名派生的数据? - How to recursively loop through files and add data derived from a certain file name in bash without using the find command?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM