Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a directory only if it exists using a shell script

Tags:

shell

I have a shell (ksh) script. I want to determine whether a certain directory is present in /tmp, and if it is present then I have to delete it. My script is:

test

#!/usr/bin/ksh
# what should I write here?
if [[ -f /tmp/dir.lock ]]; then
    echo "Removing Lock"
    rm -rf /tmp/dir.lock
fi

How can I proceed? I'm not getting the wanted result: the directory is not removed when I execute the script and I'm not getting Removing Lock output on my screen.

I checked manually and the lock file is present in the location. The lock file is created with set MUTEX_LOCK "/tmp/dir.lock" by a TCL program.

like image 291
Astro - Amit Avatar asked Dec 24 '12 11:12

Astro - Amit


People also ask

How do you delete a directory if exists in Linux?

Removing Directories with rmTo delete an empty directory, use the -d ( --dir ) option and to delete a non-empty directory, and all of its contents use the -r ( --recursive or -R ) option. The -i option tells rm to prompt you to confirm the deletion of each subdirectory and file.

How do you delete a file if exists in Shell?

You can apply the 'rm' command to remove an existing file. In the following script, an empty file is created by using the 'touch' command to test 'rm' command. Next, 'rm' command is used to remove the file, test.

How do I delete a directory in Unix shell script?

Delete a Directory ( rm -r ) To delete (i.e. remove) a directory and all the sub-directories and files that it contains, navigate to its parent directory, and then use the command rm -r followed by the name of the directory you want to delete (e.g. rm -r directory-name ).

How do you remove a file only if it exists?

Well, it's entirely impossible to remove a file that doesn't exist, so it seems that the concept of "delete a file only if it exists" is redundant. So, rm -f filename , or rm filename 2>> /dev/null , or [[ -r filename ]] && rm filename would be some options..


1 Answers

In addition to -f versus -d note that [[ ]] is not POSIX, while [ ] is. Any string or path you use more than once should be in a variable to avoid typing errors, especially when you use rm -rf which deletes with extreme prejudice. The most portable solution would be

DIR=/tmp/dir.lock
if [ -d "$DIR" ]; then
    printf '%s\n' "Removing Lock ($DIR)"
    rm -rf "$DIR"
fi
like image 126
Jens Avatar answered Sep 29 '22 21:09

Jens