Bash script to remove all files and directories except specific ones

前端 未结 5 868
无人及你
无人及你 2021-01-04 17:12

I am trying to write a very simple Bash shell script that will cd in a specific directory, it will remove all files and directories except some few selected ones and then cd

5条回答
  •  礼貌的吻别
    2021-01-04 18:09

    Two problems I can see right off the bat:

    • The -rf argument to rm must come before the filenames
    • The extglob specifiers !, (, | and ) should not be escaped with backslashes

    Try this instead:

    rm -rf !(filename1|filename2|filename3)
    

    If it's still not working, remove the -f argument, and you'll get error messages about what's going wrong instead of silently suppressing them. To print out the name of each file removed, you can add the -v option as well.

提交回复
热议问题