0

I have a subfolder of something like:

USERS = /opt/users/

I want to delete a subfolder of /opt/users without defining a new variable like:

if [ -d $USERS/phones ] && [-d $USERS/emails]; then
     rm -Rf $USERS/phones 
     rm -RF $USERS/emails
else 
     echo "Folder does not exist, continuing the process"
fi

The question is can you suggest some smarter way or is good enough? I don't know how to handle if one of the folders is not existing or if I have another && condition? and the two commands rm -Rf I am not sure of the way it looks kinda ugly. Any recommendations?

zaufi
  • 6,811
  • 26
  • 34
Rado Ratko
  • 49
  • 5
  • 1
    `-f` will cause `rm` to ignore nonexisting folders, so there's no need for those extra check, unless you have to show that log for each separate file. – 0stone0 Aug 03 '21 at 16:07

2 Answers2

2

First of all, some general bash tips:


That said, lets take a closer look at rm -f:

-f, --force

ignore nonexistent files and arguments, never prompt

So there's no need to add extra checks if the folder exists.

You can change the code to:

USERS="/opt/users/"
rm -Rf "$USERS/phones"
rm -RF "$USERS/emails"

If you want to add a echo for each file that does not exist, we'll need to check if it exist:
How can I check if a directory exists in a Bash shell script?

Using a short if/else, the code could look something like this:

USERS="/opt/users/"
[[ -d "$USERS/phones" ]] && rm -Rf "$USERS/phones" || echo '/phones does not exists'
[[ -d "$USERS/emails" ]] && rm -Rf "$USERS/emails" || echo '/emails does not exists'

The above code can be simplified by using array's:

declare -a folders=("phones" "emails")
for i in "${arr[@]}"
do
   [[ -d "$USERS/$i" ]] && rm -Rf "$USERS/$i" || echo "/$i does not exists"
done
0stone0
  • 34,288
  • 4
  • 39
  • 64
1

A variation on OP's code assuming there could be a variable number of subdirectories to remove:

users=/opt/users/                        # refrain from using ALL CAPS for user-defined variables
rmlist=(phones emails 'other schtuff')   # array of subdirectory names

for subdir in "${rmlist[@]}"
do
    [[ -d "${users}/${subdir}" ]] && rm -Rf "${users}/${subdir}" && continue
    echo "Folder ${users}/${subdir} does not exist, continuing the process"
fi
markp-fuso
  • 28,790
  • 4
  • 16
  • 36