情况:
我需要一个 bash 脚本来删除当前文件夹中的所有文件,除了名为“ .rmignore ”的文件中提到的所有文件。此文件可能包含相对于当前文件夹的地址,也可能包含星号 (*)。例如:
1.php
2/1.php
1/*.php
Run Code Online (Sandbox Code Playgroud)
我试过的:
GLOBIGNORE但效果不佳。我也尝试使用findwith grep,如下所示:
find . | grep -Fxv $(echo $(cat .rmignore) | tr ' ' "\n")
通过管道将退出传递find给另一个命令被认为是不好的做法。您可以使用-exec,-execdir后跟命令 和'{}'作为文件的占位符,并';'指示命令的结束。您还可以使用'+'IIRC 将命令通过管道连接在一起。
在您的情况下,您想要列出目录的所有内容,并一一删除文件。
#!/usr/bin/env bash
set -o nounset
set -o errexit
shopt -s nullglob # allows glob to expand to nothing if no match
shopt -s globstar # process recursively current directory
my:rm_all() {
local ignore_file=".rmignore"
local ignore_array=()
while read -r glob; # Generate files list
do
ignore_array+=(${glob});
done < "${ignore_file}"
echo "${ignore_array[@]}"
for file in **; # iterate over all the content of the current directory
do
if [ -f "${file}" ]; # file exist and is file
then
local do_rmfile=true;
# Remove only if matches regex
for ignore in "${ignore_array[@]}"; # Iterate over files to keep
do
[[ "${file}" == "${ignore}" ]] && do_rmfile=false; #rm ${file};
done
${do_rmfile} && echo "Removing ${file}"
fi
done
}
my:rm_all;
Run Code Online (Sandbox Code Playgroud)