Friday, April 26, 2024
36
rated 0 times [  36] [ 0]  / answers: 1 / hits: 8538  / 2 Years ago, thu, september 29, 2022, 9:32:20

There are plenty of situations where the use of a * is virtually inevitable - e.g. rm -rf * in a folder that holds thousands of subfolders and files.



But what if you want to exclude just one or two files or folders from the rm command? I've googled my way around and only found quite complicated solutions like find . -depth -not ( -name 'one' -o -name 'two'
-o -name 'three' ) -exec rm {} ;
as stated here.



Is there a possibility to do this in an easier way - without that detour to find?
E.g. rm -rf --exclude='one' --exclude='two' --exclude='three' * like in rsync or just rm -rf -e 'one','two','three' *?



Maybe even a general possibility to exclude things from * (so other commands like cp, mv, ... don't have to implement their own)? Something like *{'one','two','three'} or so?


More From » command-line

 Answers
2

For Bash there is a shell option called extglob that is deactivated by default to keep compatibility with standard shell syntax. Extglob complements the syntax by additional operators like !(), ?(), @() and some more.



To switch extglob on, type shopt -s extglob. To keep it switched on for the current user type echo 'shopt -s extglob' >> ~/.bashrc.



For the rm example: With extglob you can use



rm -rf !(one|two|three)

[#30062] Friday, September 30, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
afyess

Total Points: 437
Total Questions: 120
Total Answers: 107

Location: San Marino
Member since Fri, Jul 3, 2020
4 Years ago
afyess questions
;