Dumb Shell Tricks no.3 Automation
Created //
Automation in the shell
To start with, you're going to want to learn how to use for
. It'll let you apply some command to a group of files. There are other ways to do this, but this is the easiest to get started with.
I want to zip up each folder into its own zip file
Assume I'm in a folder and I have something like this:
/project1
/project2
/project3
/somefile.txt
/something-else.txt
Each one of those project folders has lots of files and folders inside. I want to turn each one of them into its own zip file. (Maybe for backup, archiving, sending to someone else, etc.)
Using the GUI you'd typically have to do it one by one. What if you have 100 folders? This is easy in the shell...
$ for i in *; do zip -r "$i.zip" "$i"; done
That will give me:
project1.zip
project2.zip
project3.zip
somefile.txt.zip
something-else.txt.zip
That will work, but it will also catch other files in the folder that you may not want to zip. (Like those .txt files.)
So how do you make it just zip up the folders in the current directory?
$ for i in */; do zip -r "${i%/}.zip" "$i"; done
Now I'll just get:
project1.zip
project2.zip
project3.zip
How do you remove the "MACOSX" files inside a zip file?
If you've ever zipped up a folder on a Mac, you may have noticed extra files in there that you didn't add. I'm referring to the "MACOSX" files that are hidden by default. You can remove them without consequence.
$ zip -d filename.zip "__MACOSX*"
The 'for' loop
The basic structure is:
for (some things); do (some commands); done
A simple example is to print the names of all files in the current folder that end in ".txt". E.g.:
$ for i in *.txt; do echo "$i"; done
But getting that list of "some things" can also be the result of a more complete command. For example, using find
and maybe combining it with grep
. E.g., Find all ".txt" files that have the word "invoice" in them.
$ for i in $(find . -name "*.txt" | grep invoice); do echo "$i"; done
And that's it for now...
Virtually everything you can do in the shell you can automate. It's worth learning!
As for learning the shell, there are lots of resources available online.
// ka