Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

42 Astoundingly Useful Scripts and Automations for the Macintosh
42 Astoundingly Useful Scripts and Automations for the Macintosh
42 Astoundingly Useful Scripts and Automations for the Macintosh
Ebook413 pages5 hours

42 Astoundingly Useful Scripts and Automations for the Macintosh

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Forty-two astoundingly useful scripts and automations for your Macintosh. Work faster and more reliably. Use Perl, Python, AppleScript, Swift, and Automator to automate the drudgery of computer use. Work on the command line, add actions to the services menu and the menu bar, and create drag-and-drop apps.

Create ASCII art and music, build talking alarms, and roll dice.

Play your music backward.

Preflight your social media comments.

Display your to-do list on your desktop.

And of course, manage your favorite recipes. That's what computers are for.

Get your retro on and bring your Macintosh into the world we were promised, a world of personal computers, where your computer is yours to control. You have the technology. You have the source code. The era of the home computer awaits.

LanguageEnglish
Release dateAug 1, 2019
ISBN9780463422823
42 Astoundingly Useful Scripts and Automations for the Macintosh
Author

Jerry Stratton

Jerry Stratton writes at Mimsy Were the Borogoves on politics, technology, and programming for all. He has a Bachelor's degree in Psychology from Cornell University and studied guitar at the Musicians Institute of Technology in Hollywood, California. He has appeared in at least one bad movie from the eighties and participated in at least one ill-fated pre-Internet hypermedia startup.

Read more from Jerry Stratton

Related to 42 Astoundingly Useful Scripts and Automations for the Macintosh

Related ebooks

Programming For You

View More

Related articles

Reviews for 42 Astoundingly Useful Scripts and Automations for the Macintosh

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    42 Astoundingly Useful Scripts and Automations for the Macintosh - Jerry Stratton

    42 Astoundingly Useful Scripts and Automations for the Macintosh

    Jerry Stratton

    42 Astoundingly Useful

    Scripts and Automations

    for the Macintosh

    by Jerry Stratton

    ©2020 Jerry Stratton

    First published August 2019

    ISBN 978-1-09-351533-6 (print)

    ISBN 978-0-46-342282-3 (ePub)

    http://AstoundingScripts.com/

    The supreme joy of learning to program a computer comes when the learner begins to formulate new problems to solve.—James S. Coan, Basic FORTRAN

    5 6 7 8 9

    20 21 22 23 24 25 26 27 28 29

    While the advice and information herein are believed to be true and accurate as of the date of publication, and especially with regard to macOS Catalina, 10.15.6, all courses may run ill, and the author makes no warranty, express or implied, with respect to the material contained within this deeply invaluable book.

    To Douglas Adams, who dared us not to panic in the face of complexity. And to demand the right to open the windows.

    The major difference between a thing that might go wrong and a thing that cannot possibly go wrong is that when a thing that cannot possibly go wrong goes wrong it usually turns out to be impossible to get at and repair.—Douglas Adams, Mostly Harmless

    Introduction

    I’ve been researching the dawn of the home computer for a novel. I was inspired, in the best traditions of writerly procrastination, to write a book that emulates the books I’m reading. In the seventies and eighties there were dozens of books about how to control your home computer. 57 Practical Programs & Games in BASIC. 24 Tested, Ready-to-Run Game Programs in BASIC. 32 BASIC Programs for the TRS-80 (Level II) Computer. More than 32 BASIC Programs for the Commodore 64.

    They all had in common the assumption that the best way to learn is by doing. That you want to learn. That you want to be in charge of your computer. And that you were willing to learn by typing the programs into your computer, often customizing them for your own unique needs as you typed them in.

    This was a time when the line between using your computer and programming your computer was thin. You used your computer by programming it. And if you could do it to your computer, you could tell your computer to automate itself and do it on its own.

    BASIC is no longer the lingua franca of the home computer world. You can use BASIC if you wish—on macOS or iOS, there’s ChipMunk BASIC and HotPaw BASIC, for example—but your Macintosh comes equipped with more powerful languages that are easier to use and maintain. Most of my scripts are written in Perl and Python. Some are written in AppleScript, JavaScript, and Swift. Some are written in Automator’s or Nisus Writer Pro’s or Zsh’s batch and macro languages. Don’t worry if you don’t know what some or all of those terms mean. You don’t have to to use these scripts—or even to customize them. You need only a love of experimentation.

    Where it makes sense, I’ve provided a sample session for the script and a description of how the script works, so you can more easily use its techniques in your own scripts. But this is not a book about programming; it is a book about utility.

    All of these scripts are useful to me. I use them while writing; I use them while browsing the web and while commenting. I use them to prepare for role-playing games, to prepare music for road trips, and to organize my to-do lists. They’re reasonably short, especially compared to some of the old BASIC listings we had to type from magazines and books back in the day. You can easily enter them yourself, or you can copy them from the eBook. In either case, you have the source code here for examining, for learning, and for customizing, in the privacy of your home computer.

    Begin at the beginning, the King said gravely, and go on till you come to the end: then stop.—Lewis Carroll, Alice’s Evidence

    Talk to me in thirty minutes

    The traditional first program is hello world. The programmer, Frankenstein-like, programs their computer to announce that the computer is alive by printing hello, world to the screen. Let’s do hello world one better. In your Applications folder, there’s a Utilities folder. You can find the Terminal app there. The Terminal opens up the world of scripting. Double-click the Terminal—or type COMMAND-SPACE, type Terminal, and press return—to start up the Terminal. Once you have the command line, type say Hello, World after the percent sign prompt:

    % say Hello, World

    %

    Your Macintosh will speak the phrase, hello, world. If it doesn’t, check your volume level. You can use say anywhere on the command line. If you want an audible notice that another script is finished, add ;say done to the end of it, and it will literally say the word done when the script is done.

    We can make it even more useful. Perhaps a 30-second timer?

    % sleep 30;say Time’s up.

    %

    After 30 seconds, your computer will tell you your time’s up. You can type this line, go off to do something else, and your computer will speak to you to remind you that you only meant to work for 30 seconds, or 600 seconds, or 3600 seconds.

    But of course it would be nicer to tell it to wait 10 minutes, or an hour, perhaps with a countdown. This is what scripts are for: they leverage simple programs that already exist on your computer for more complex purposes.

    The following steps will (1) create a folder called bin for storing your scripts, (2) create an empty script file called alarm, (3) tell your computer that this new file is a script file, and (4) open TextEdit to edit the script.

    % mkdir -p ~/bin

    % touch ~/bin/alarm

    % chmod u+x ~/bin/alarm

    % open -t ~/bin/alarm

    %

    When TextEdit opens, type the code at the end of this chapter. When you’re done typing, test it:

    % ~/bin/alarm It’s rabbit-chasing time. --countdown 30 minutes

    00:00:00

    %

    The three sets of zeroes are the end of the countdown. The countdown writes over itself every second, so as not to fill the screen with silly countdowns. It does this using \r rather than the \n you’ll see most often in Perl. Backslash-r is a return; it returns the cursor to the beginning of the line without moving to a new line as backslash-n does. You’ll see similar variations throughout these scripts.

    If a countdown is distracting, leave it out.

    % ~/bin/alarm 15 minutes 'Go read a book!'

    %

    You may find, as in the above, that the computer doesn’t always pronounce words correctly. English is famous for its confusing logic. You can fix its pronunciation by misspelling words, for example, replacing read with reed. You can also use special phoneme codes; go to astoundingscripts.com/phonemes and you’ll be redirected to Phonemes in Apple’s Speech Synthesis Programming Guide.

    You are likely to be tempted to use exclamation points to make your computer more emphatic. However, exclamation points are special characters in Terminal. You should avoid them on the command line. You can, however, prepend exclamations with backslashes or, as above, surround the text with single quotes instead of double quotes.

    This script uses Perl’s printf to format the countdown. Single-digit numbers are not normally displayed with a zero in front of them. The format code %02i tells printf that this is a two-digit integer, and ensures that the number is always two digits by prefixing 0 if necessary. There are three percent codes in the printf, one for each of the hours, minutes, and seconds remaining in the countdown.

    Here’s another trick: you can continue using the Terminal window for other things, if you don’t want a countdown. Add an ampersand at the end of the script, and it won’t bother you until it has some output.

    % ~/bin/alarm 45 seconds&

    [1] 1435

    %

    When you use an ampersand to send the script to the background, it gives you two numbers that can be ignored, the job number in brackets, and the process identifier after the brackets. The ability to work in the background is one of the reasons command-line scripts and programs are often not very talky; messages popping up from the background while you’re working are very distracting.

    You can even exit the Terminal window and the script will still be there to talk to you when the timer ends. But you must exit from the command line; if you close the window by clicking the red button or using COMMAND-W, your Mac will warn you about killing the process and, if you continue, will in fact do so, resulting in no alarm.

    Important Variables

    Code: alarm

    #!/usr/bin/perl

    # a talking timer

    # Jerry Stratton astoundingscripts.com

    $duration = 60;

    $period = 'seconds';

    $countdown = 0;

    while ($option = shift) {

    if ($option =~ /^[1-9][0-9]*$/) {

      $duration = $option;

    } elsif ($option =~ /^(second|minute|hour)s?$/) {

      $period = $1;

    } elsif ($option =~ /^-(c|-countdown)$/) {

      $countdown = 1;

    } elsif ($option =~ /^-(h|-help)$/) {

      help();

    } else {

      $alarm .= $option ;

    }

    }

    $duration *= 60 if $period eq 'minute';

    $duration *= 3600 if $period eq 'hour';

    $alarm = Time's up. if !$alarm;

    if ($countdown) {

    #countdown doesn't use newlines; tell Perl to print anyway

    $| = 1;

    $endTime = time() + $duration;

    while (time() < $endTime) {

      $seconds = $endTime-time();

      $hours = int($seconds/3600);

      $seconds -= $hours*3600;

      $minutes = int($seconds/60);

      $seconds -= $minutes*60;

      printf %02i:%02i:%02i\r, $hours, $minutes, $seconds;

      sleep 1;

    }

    print 00:00:00\n;

    } else {

    sleep $duration;

    }

    `say $alarm`;

    sub help {

    print qq($0 [period] [alarm text]: speak an alarm after xxx period. Default $duration seconds, $alarm.\n);

    print \tperiods: second, seconds, minute, minutes, hour, hours.\n;

    print \t-c/--countdown: countdown to zero on command line.\n;

    print \t-h/--help: print this help text.\n;

    exit;

    }

    The computer should be doing the hard work. That’s what it’s paid to do, after all.—Larry Wall, Usenet, 1997

    A Diversion About: Typing

    This is not a book that teaches you to program. It provides you with useful scripts through which you can teach yourself programming, or which you can type in and use. If you don’t want to teach yourself programming, you still have Forty-two useful scripts.

    But as you use these scripts you will probably want to change them. There is an immediacy about the command line that encourages playfulness in programming. You're on the command line, running a program, and you realize, I need this new feature. You invoke your text editor and add the new feature. You test the feature and are satisfied, or you refine it further. One of the strengths of macOS is, it merges the command line and the GUI in a way that preserves the usefulness of each. You can use command line editors; you can pretend your GUI editor is a command line editor, invoking it from the command line, editing your script and saving it, and going right back to the command line. All code flows to the great magnet. On macOS it’s the Terminal application. Terminal is in the Utilities folder of your Applications folder, or you can use COMMAND-SPACE and search for Terminal.

    Most of these scripts work from the Terminal. You will probably want to drag the Terminal’s icon to your Dock.

    From the Terminal, you can do many things in text that you already do using your mouse and the graphical interface of your Macintosh. You can cd to change to a new directory. You can mkdir new folders, and ls to list your files. They’re the same files you see in the Finder on your Mac.

    Other apps sit on top of your computer screen and let you do things to your computer. Type a document. Draw a picture. View photos or listen to music. The Terminal is not on top of your computer but rather inside; it is a window to your computer's soul. Your computer has a soul of clay, and you are its potter.

    In the sample runs in this book, things you type come after a percent sign. You don’t type the percent, but what comes after it on the same line, followed by the return key.

    % cd ~/Documents

    % ls

    3D Stuff      Finances        RPG

    Angband        Friends          Reading

    Apache        Internet        Safari

    Backups        Collections      Negative Space

    Writing        Nisus Documents  Notes

    Eudora Folder  Programming

    %

    Ah. Eudora folder. I'd forgotten about you. Computers do not believe in reincarnation, but they do believe in past lives. You will see different things in your Documents folder than I see in mine. Same for your Desktop.

    % cd ~/Desktop

    % ls

    You should see the same files in the Terminal that you see on your Desktop. Your Desktop is just another folder on your Mac.

    You must use a text editor to create your scripts. The Macintosh comes with TextEdit. If you followed the instructions in the previous chapter, you invoked TextEdit via the fourth of the four lines of code necessary to create a script. But running four lines of code every time you want to create a new script is nuts. Scripts are supposed to reduce work, not make more. Let’s create a script called edit to handle those four lines.

    % mkdir -p ~/bin

    % touch ~/bin/edit

    % chmod u+x ~/bin/edit

    % open -t ~/bin/edit

    After each line, type the return key. At this point, you are in TextEdit. In the empty TextEdit window, type these lines, pressing the return key at the end of each:

    #!/bin/zsh

    #edit a script file

    mkdir -p $HOME/bin

    FILE=$HOME/bin/$1

    touch $FILE

    chmod u+x $FILE

    open -t $FILE

    Save, and close TextEdit. Whenever you want to create or edit a command-line script (one with a shebang line), type:

    % ~/bin/edit

    Replace with the name of the script you want to edit or create. If you want to edit or create the anagrams script from Verify anagrams on page , type ~/bin/edit anacheck. If you want to edit the voices script from A Diversion About: History on page , type ~/bin/edit voices.Try now by using edit on edit itself:

    % ~/bin/edit edit

    TextEdit should open and display the code you’ve already typed. Now, what does this code mean? How do scripts work?

    1. Every script you want to use from the command line must tell the command line what scripting language it uses. That’s what the pound sign-exclamation point line—the hash-bang, or shebang—does. It tells the command line that this script needs /bin/zsh.

    2. The way to run a script is to type the name of the script, along with where the script is located. The first part, ~/bin/, is the path to where the script is located. The second part, edit, is the name of the script.

    3. The third part, also edit, is the argument, or parameter, for the script. That is the part where you tell the script what you want it to do. All scripts have a location and a name, but not all have an argument. Some have more than one argument, some have none.

    4. It is imperative, when you type, that you type exactly the letters and numbers in the script. The capital letter "O is not the same as the number 0. Likewise, the capital I, the lowercase l and the number 1" are all different. I chose the font for code in this book so that all such characters have different shapes.

    5. It is important, for both your readability and, in some cases, for the code to work, that the lines be indented as displayed. Use the tab key to indent; no line is indented by more than one tab extra than the previous line.

    Most of your scripts go in your bin folder. You can think of it as a bin to store scripts, but of course that has nothing to do with how it got its name. In one of your Mac’s past lives, there were no scripts. There was only text documents or unchangeable code compiled to uneditable binary. The word bin is short for binary even though very little binary code goes in bin nowadays.

    There is a lot of typing in this book. Now that you have the edit script, you don’t have to type. You can copy and paste from the eBook. Should you type, or should you copy? Type if you learn by typing. As you see the script slide beneath your fingers, you will learn how you might modify it. You will learn because you will make mistakes, and will need to study the script to find where you made the mistake.

    Type or not; it’s up to you. You know best how you learn. Regardless of whether you type the code, or copy and paste it,

    Enjoying the preview?
    Page 1 of 1