简体   繁体   中英

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.). 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 {}" \;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM