If you’ve been following along at home, you’ll have made several changes to your Mac via the Terminal app. Surely you’re tracking all these changes on a spreadsheet, right? I mean, what if you wanted to go back and find out what changes you’ve made? How else would you track it than by laboriously typing out each change by hand in some sort of database? Well, today’s tip will show you how to automate this process and put all your changes into a text file automatically.
To start, we’re going to make use of the history command in Terminal. Launch the app from your Utilities folder (typically in the Applications folder) and type the word
history, then hit return. Terminal will then list up to the last 500 commands that you’ve put through it.
That could be a lot of filler, though, so let’s just focus on the defaults write commands we’ve been issuing in this tips column. Using grep, a command-line utility for searching for specific text strings, we can filter out the history list to just those specific commands. Type the following into Terminal and hit the Return key:
history | grep "defaults write"
You’ll get a nice list of only the commands that show you the defaults write commands you’ve issued in Terminal. What you may realize, though, is that after you’ve issued 500 commands, the first ones will disappear from this list. Here’s a command that will create a text file that saves all the results from your grep search:
history | grep "defaults write" >> ~/Documents/defaultsLog.txt
This puts the search results into a text file, called ‘defaultsLog.txt,’ and places it in your Documents folder. Now comes the tricky (and super cool) part. Head over to your Applications folder once more and open TextEdit. Choose Open from the File menu and navigate to your home folder. Press Command-Shift-Period to show hidden files, and then choose the .bash_profile file from the resulting list. If it isn’t there, create a new file in your home folder, name it .bash_profile, and then open it as above. Then add the following code to the end of the file (or the beginning if you just created a blank one):
PROMPT_COMMAND='echo "$(history 1 | grep "defaults write")" | sed '/^$/d' >> ~/Documents/defaultsLog.txt'
This script will now add to the list document you created in the step above every time a new command prompt is shown in Terminal. Pretty slick, huh?
- Via Mac OS X Tips