在bash shell脚本中,do-for.sh
我想使用bash在glob中命名的所有目录内执行命令。这已经被无数次的回答,但是我想在命令行上提供命令本身。换句话说,假设我有目录:
foo
bar
我要输入
do-for * pwd
并让bash在内部foo
然后在内部bar
打印工作目录。
通过阅读网络上的众多答案,我认为我可以做到:
for dir in $1; do
pushd ${dir}
$2 $3 $4 $5 $6 $7 $8 $9
popd
done
显然,尽管全局已*
扩展为其他命令行参数变量!因此,第一次循环,正如$2 $3 $4 $5 $6 $7 $8 $9
我所期望的那样,foo pwd
但相反,我得到了foo bar
!
如何避免将命令行上的glob扩展为其他参数?还是有更好的方法来解决这个问题?
为了使这一点更清楚,这是我要使用批处理文件的方式。(顺便说一下,这在Windows批处理文件版本上工作正常。)
./do-for.sh repo-* git commit -a -m "Added new files."
我假设您对必须提供某种分隔符的用户开放,像这样
./do-for.sh repo-* -- git commit -a -m "Added new files."
您的脚本可以做类似的事情(这只是为了解释概念,我没有测试实际的代码):
CURRENT_DIR="$PWD"
declare -a FILES=()
for ARG in "$@"
do
[[ "$ARG" != "--" ]] || break
FILES+=("$ARG")
shift
done
if
[[ "${1-}" = "--" ]]
then
shift
else
echo "You must terminate the file list with -- to separate it from the command"
(return, exit, whatever you prefer to stop the script/function)
fi
此时,您将所有目标文件放在一个数组中,并且“ $ @”仅包含要执行的命令。剩下要做的就是:
for FILE in "${FILES[@]-}"
do
cd "$FILE"
"$@"
cd "$CURRENT_DIR"
done
请注意,该解决方案的优势在于,如果您的用户忘记了“-”分隔符,则会收到通知(而不是由于引用而导致的失败)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句