Search code examples
bashsudo

how to truncate on glob files through sudo?


I need to truncate a big bunch of files with sudo. For only one this works:

sudo truncate -s 0 /var/lib/docker/containers/1cdd2386de3579-json.log

But with a glob like this /var/lib/docker/containers/*/*-json.log ...

$ LANG=C sudo truncate -s 0 /var/lib/docker/containers/*/*-json.log
truncate: cannot open '/var/lib/docker/containers/*/*-json.log' for writing:No such file or directory

Solution

  • The globs are evaluated in the shell of the current user, before the elevated permissions of sudo are in effect (before the actual execution of sudo). The current user probably doesn't have permission to access the affected paths.

    You can run it in a sh shell, that way the globs will be evaluated inside sudo's shell:

    sudo sh -c 'truncate -s 0 /var/lib/docker/containers/*/*-json.log'