Removing directory contents recursively

Hi all, still struggling with this.
I want to run command rm -rf /path/to/dir/*, so that I delete the content but not the dir itself. I get this

julia> Base.run(`rm -rf $(ReproData.root())/code/"*"`)
Process(`rm -rf '/Users/floswald/git/ReproWorkshop/code/*'`, ProcessExited(0))

but that does not work because this '/Users/floswald/git/ReproWorkshop/code/*' is different from /Users/floswald/git/ReproWorkshop/code/*. The problem is the star character:

julia> Base.run(`rm -rf $(ReproData.root())/code/*`)
ERROR: LoadError: parsing command `rm -rf $(ReproData.root())/code/*`: special characters "#{}()[]<>|&*?~;" must be quoted in commands

how to do this quoting properly?

thanks

It has nothing to do with quoting. As explained in the old thread you just resurrected, wildcards like * are a feature of a shell, not a feature of rm, so you need to execute a shell, e.g.

run(`sh -c "rm -rf $(ReproData.root())/code/*"`)

Of course, this is not portable because not all systems have sh or rm. You could also do it in Julia, something like:

foreach(readdir(joinpath(ReproData.root()), "code"), join=true)) do filename
    rm(filename, recursive=true, force=true)
end

or using the Glob.jl package for more flexibility.

PS. Note that using shell globbing like * has been discussed extensively. See also Is there any way to run an external command with * in it? and How to use * with backticks and Delete a file from script using wildcards? and Executing system commands "backtick-like" way in Julia? … if an old thread does not clarify things for you, please do not comment on an old thread with new questions. Create a new thread, explain your question, and feel free to link other threads that might be relevant.

3 Likes

oh right! sorry I didn’t get the bash call there in front. thanks a lot!

I don’t understand the need for an IOBuffer in that example. Why not just define a string with the desired script directly and pass it to powershell, rather than writing a string to a buffer and then converting back to a string?

1 Like

To remove everything under a directory dir_path, isn’t it enough to write in Julia:

rm(dir_path, recursive=true, force=true)

That will remove the directory too, which the OP doesn’t want.

OK, thanks, even if that would be just a mkdir(dir_path) away.