0

I have a deployment script that removes all files in a tmp folder before continuing, but sometimes during the deployment, a process will use one of the tmp files, making the rmcommand fail. This is how my script looks like

rm -rf app/tmp
tar -xf app.tar

That is an over-simplification of what is happening, please don't try to suggest improving the deployment process, this is strictly a question about the rm command

I am thinking of something like

# pseudo code
while [[ ! rm -rf app/tmp ]]; do sleep 1; done
tar -xf app.tar

In other words: continue to try to delete folder until nobody added files there, then continue the script.

Do you know of a syntax that would allow this in bash?

Currently the script fails and never extracts the tar files.

Thanks for your input here.

santiago arizti
  • 435
  • 6
  • 16
  • 1
    If you were to remove `test`(1) (aka `[`) from your "pseudo code", I believe it would work in bash (ie, `while ! rm -rf app/tmp; do sleep 1 ; done`). – Håkan Lindqvist Aug 12 '19 at 19:31

2 Answers2

1

The while loop isn't comparing anything. It needs to match on something; in this case, we want to know if the directory exists. If it exists, delete it with rm, otherwise if doesn't exist, exit the loop and run the tar command. You don't want to use the rm command inside the while condition.

# pseudo code
while [[ -d app/tmp ]]; do rm -rf app/tmp; sleep 1; done
tar -xf app.tar
ansible
  • 11
  • 3
  • 1
    I was looking more forward to a solution checking the out status of rm, but this will do – santiago arizti Aug 12 '19 at 21:20
  • sorry I removed this as accepted answer, but I thought that even though your answer solves the problem in question, a more general answer is found in another question from SO, I posted it below – santiago arizti Aug 12 '19 at 21:31
  • If you use the -f option with `rm` with this code example, it will always work, because the "force" option does not prompt and ignores files that don't exist. The `rm` command as written should always complete. – ansible Aug 12 '19 at 21:31
  • my problem was that during the command some other process adds a content into the tmp dir, this is the output of the command, thus making my complete cron fail:``rm -rf app/tmp/* rm: cannot remove ‘app/tmp/dir1’: Directory not empty`` – santiago arizti Aug 12 '19 at 21:35
1

Looks I found the answer in another question "How can you run a command in bash over until success"

https://stackoverflow.com/a/5274386/2296642

I should use until syntax.

until rm -rf app/tmp; do echo trying again; done
tar -xf app.tar
santiago arizti
  • 435
  • 6
  • 16
  • also, it seems I could have accomplished the same thing as I wanted with `while` by skipping the `test`(`[`) command with `while ! rm -rf tmp/; do echo trying again; done` – santiago arizti Aug 12 '19 at 21:38