Monday, May 20, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 2215  / 2 Years ago, fri, march 11, 2022, 12:53:57

I can move files in the terminal easily enough. I have a whole mess of stuff submitted by students daily and it'd make my life a lot easier to have one thing I can run of an evening that'll move all the photo submissions (JPGs and PNGs normally) to one directory, and all the text stuff to another.



I could write something basic with mv *.jpg kind of commands but if there aren't any of those types of file there then I'm assuming the entire script would fail and the whole time-saving exercise would be pointless.



To add a complication, a couple of my higher students submit in zip's so I'd like to be able to make the script extract them out first.



So, TL;DR - extract zips & move files without being stopped for errors caused by there not being a particular type of file.


More From » command-line

 Answers
1

I'm assuming the entire script would fail




It won't, only that single command would "fail" (meaning the *.jpg globbing pattern will be expanded to a literal *.jpg, which will make the command throw an error in case a file named *.jpg doesn't exist), but the script will keep executing despite the error. So in most cases that's not a concern, however if you want to do things The Right Way™, enable failglob before running the commands containing the globbing patterns:



shopt -s failglob


From Bash Reference Manual: Filename Expansion:




If the failglob shell option is set, and no matches are found, an error message is printed and the command is not executed.




To extract all the .zip files in the current working directory to a single directory:



unzip '*.zip' -d /path/to/target/directory


Notice that *.zip is enclosed in single quotes, so that unzip can expand the pattern on its own (the command would fail otherwise).



Putting everything toghether:



#/bin/bash
shopt -s failglob
mv *.jpg /path/to/target/directory
mv *.png /path/to/target/directory
unzip '*.zip' -d /path/to/target/directory

[#15738] Friday, March 11, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
thellfi

Total Points: 222
Total Questions: 103
Total Answers: 123

Location: Palau
Member since Mon, Aug 16, 2021
3 Years ago
;