Friday, May 3, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 863  / 3 Years ago, wed, august 4, 2021, 5:23:55

Say I have the following files:



foo.coffee
foo.js
bar.js


Is there an easy way how to rm *.js if there's a corresponding .coffee file? In the example such a command would remove foo.js leaving:



foo.coffee
bar.js


I'm looking for some sort of a rm wrap as I need to do a recursive rm -r.


More From » bash

 Answers
6

A little bit of (using all the best practices!):



shopt -s nullglob

for f in *.js; do
coffee=${f%.js}.coffee
[[ -f $coffee ]] && rm -v -- "$f"
done



  • nullglob is a shell optional behavior so that *.js will expand to the empty string if there are no files with extension js.

  • Use shell parameter expansion to remove the extension .js and replace it with .coffee in the variable coffee.

  • rm is used with the -v switch (verbose) so that you see what's happening.

  • rm is also used with -- that marks the end of options, just in case there's a file that starts with a hyphen: in that case, rm would be confused and try to interpret an option.

  • The [[ ... ]] construct is a conditional construct and uses conditional expressions. Notice I'm using the robust double square bracket [[ and not the single [. Very good practice (in ).

  • Note that the quoting is perfect. It's all 100% safe regarding files that have spaces or funny symbols in their name.



For testing purposes, you should put echo in front of rm:



    [[ -f $coffee ]] && echo rm -v -- "$f"


so that it only echoes the command and doesn't remove anything. When you're happy with that, remove the echo.



Enjoy!


[#30528] Thursday, August 5, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ainlyyor

Total Points: 210
Total Questions: 129
Total Answers: 116

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
;