A really simple solution is to remove pkgs
after deleting files in the current directory which are also present in the subdirectory.
shopt -s nullglob dotglob # Bash extension: see below
for f in pkgs/*; do
rm ./${f#pkgs/}
done
rm -rf pkgs
Tangentially, don't use ls
in scripts.
If you want to keep the files in a variable for some reason (like, maybe pkgs
was removed for other reasons during some other processing which you did not elaborate on in your question; or maybe other temporary files are added during processing which should also be removed), use an array instead of a string variable. (This is not compatible with POSIX sh
, but your question is tagged bash.)
shopt -s nullglob dotglob
filesToKeep=(./*)
:
: other processing ...
:
theseFiles=(./*)
for file in "${filesToKeep}"; do
for i in "${!theseFiles[@]}"; do
[[ "${theseFiles[i]}" = "$file" ]] && unset 'theseFiles[i]'
done
done
rm "${theseFiles[@]}"
(Array outer join implemented based on Remove an element from a Bash array)
If you don't want to use shopt -s dotglob
for some reason, you need to use multiple wildcards to include dot files in the results. Properly speaking, the correct expression would be something like
pkgs/..?* pkgs/.[!.]* pkgs/*
but in practice, you might want to exclude ..?*
if you are lazy and/or know for certain that there will be no files whose names start with two dots. (You need to exclude the parent directory from the matches, but include other files which start with dots.)
shopt -s nullglob
avoids having any of the wildcards expand to itself if there are no matches.