'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.
Solution 1:[1]
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 {}" \;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew Vickers |
