/stuff/a dir/
/stuff/b other/
/stuff/c/
我需要在Bash脚本中调用:
script.py "a dir/" "b other/" "c/"
或者,更替代地说,转义空格:script.py a\ dir/ b\ other/ c/
我需要确保脚本仅针对目录“stuff”被调用一次。
有没有简单的方法可以实现这种要求?我已经在Google上查找了一些信息,最好的解决方案是需要我知道有多少个目录。
/stuff/a dir/
/stuff/b other/
/stuff/c/
我需要在Bash脚本中调用:
script.py "a dir/" "b other/" "c/"
或者,更替代地说,转义空格:script.py a\ dir/ b\ other/ c/
我需要确保脚本仅针对目录“stuff”被调用一次。
有没有简单的方法可以实现这种要求?我已经在Google上查找了一些信息,最好的解决方案是需要我知道有多少个目录。
find /stuff -type d -exec script.py {} +
当你使用-exec
时,花括号{}
会被替换为匹配文件的名称,而+
表示命令的结束(如果您想告诉find执行其他操作)。这是使用find执行命令的理想方式,因为它可以正确处理具有不寻常字符(例如空格)的文件名。
find相当灵活,特别是如果您拥有通常捆绑在Linux发行版中的GNU版本。
# Don't recurse into subdirectories.
find /stuff -maxdepth 1 -type d -exec script.py {} +
# Pass in a/, b/, c/ instead of /stuff/a/, /stuff/b/, /stuff/c/.
find /stuff -type d -printf '%P\0' | xargs -0 script.py
在第二个例子中,注意仔细使用\0
和xargs -0
来使用NUL字符作为文件名的分隔符。虽然可能看起来很奇怪,但这样可以使命令即使在您的目录名称中使用新行\n
之类的非常规字符时也能正常工作。
# Start with an empty array.
DIRS=()
# For each file in /stuff/...
for FILE in /stuff/*; do
# If the file is a directory add it to the array. ("&&" is shorthand for
# if/then.)
[[ -d $FILE ]] && DIRS+=("$FILE")
# (Normally variable expansions should have double quotes to preserve
# whitespace; thanks to bash magic we don't them inside double brackets.
# [[ ]] has special parsing rules.)
done
# Pass directories to script. The `"${array[@]}"` syntax is an unfortunately
# verbose way of expanding an array into separate strings. The double quotes
# and the `[@]` ensure that whitespace is preserved correctly.
script.py "${DIRS[@]}"
for f in stuff/*; do
if [ -d "$f" ]; then
./script.py "$f"
fi
done
script.py $(find /stuff/* -type d)
如果您担心空格和其他特殊字符,可以这样操作:
script.py $(find /stuff/* -type d | while read line; do echo "\"$line"\"; done)
find /stuff/* -type d -maxdepth 1 -print0 | xargs -0 script.py
这将查找 /stuff 下的所有目录,但不递归,并将它们传递给 script.py,并确保即使目录名称中有空格也能正确传递。
find
命令具有一些特别有用的功能,用于处理文件;比“内置”命令更加实用,例如在处理空格嵌入的文件名时(请参见man find
中的-print0
),以及执行exec
命令.. 有关内置命令的如何/什么/为什么的更多信息,请参见:http://unix.stackexchange.com/questions/11454/what-is-the-difference-between-a-builtin-command-and-one-that-is-not - Peter.Ofind
命令,它更冗长而已。 - John Kugelman