Category Archives: Shell Games & Scripts

Renaming in Python

I needed to rename several files.  I thought perhaps using a script would make it a little faster.  Well, the renaming went faster.  Writing the script of course took much longer.  But I suppose I learned something.

The image files were individual pages from a book of about 64 pages.  They were named one number off from their actual page numbers.  You can imagine how annoying that can be.  You can’t?  Well, try harder.  It’s pretty annoying when 3 isn’t three but 4.  Three isn’t four!

That doesn’t irritate you?  Well, I wrote a script to fix it nonetheless.

You can find the script over at my GitHub.

It’s modifiable enough so perhaps it can suit your needs.  Feedback is always welcome.


Take Multi-Line User Input and Add that to a Variable in Bash

We are using a construct using xargs and ctrl-d for breaking.  I’m not perfectly satisfied with it, but it certainly does the job of taking multi-line user input and stuffing that into a variable (formatting intact).

(The first and third assignments add quotes around the contents of the xargs input.  You may or may not require that.  In our case the variable is the body of a message sent by mail.  It must be quoted.)

printf '%s\n' "What would you like the body of the message to contain?  " 
printf "\\033[1mWhen finished hit ctrl-d on a new line to proceed.\\033[0m  \\n\\n" 
# this will load the user's input into a variable instead of a file 
reminderBody+=$( xargs -0 ) 

This basic construct could be used for a variety of needs.

(The \033[0m‘s are used to change font colors. Again, optional.)


NTP and the Delay

We were setting up a check to ensure our time servers were pointed correctly from the firewall, but the standard time query was taking six seconds for each check.  With four time servers that’s nearly thirty seconds to make a simple “are you there” sort of check.  We didn’t want to do a simple ping test since this would not ensure the machine queried was in fact an actual time server.

After some digging and testing we found that if we limited the packets to a single packet the test was instantaneous.  So we added the -p argument and called it good.  (In our case we were not concerned with checking the time status but rather only the status of the server as an available time server.)

This is the basics of the command:

time ntpdate -qp

And that’s about it.  Very much faster with the p in the mix.


Get git on a Server of Your Own

The trouble with searching the Web for instructions relating to git and using your own git server is that mostly you will find articles for working with someone else’s repository server (like GitHub or so many others).  You can find quite good instructions for interacting with a remote server from your local development machine, but there are so many such instructions out there that locating useful information about using your own server to host git gets buried pretty deep.

Let’s go over some of the most basic pieces, and if you know how to use git with someone else’s repository server then you will be in good enough shape to sort out your specific situation.

First we need to differentiate between the served repository and any local copy of the files you might like to keep.  You don’t necessarily need to keep a local copy of the files on the server since the repo contains enough information to rebuild the files at any point, but I’m going to show you how because I wanted mine to include server-held local copies of the files.

On your server you’ll want to create a bucket for holding any and all of your git repositories (I broke mine into projects plus an archive folder).  So your paths may look like this:


In the above example, the folder I’ve called git is just the bucket which holds the local copies of the repository files, and should not be used itself as a repository.  (If you are only planning a single repository I would still recommend using this structure as a way of being ready for the future.)  The folder I’ve called .repos is the bucket which contains the git repositories; these sub-folders do not contain any of the actual files but rather just diffs which allow git to rebuild the files at various stages.  You will see that I have a one-to-one correspondence between the .repos sub-foldders and the local copy folders above.

Move into each directory under .repos in turn and perform these actions.  Here we will just pick project1 and go through the steps.

cd /media/storage/git/.repos/project1
git init --bare

This will create an empty repository which you can clone, add files, and make commits.  This is how to make your first copy (of the empty repo) and add files.

cd /media/storage/git
git clone yourusername@localhost:/media/storage/.repos/project1
# now move into the newly cloned directory... 
cd project1
# here you will want to add any existing files to this folder or create a new file then...
git add .
git commit -m "initial commit of new repo"

Now you have a good master to begin.

From your laptop or workstation or any other computer you can perform these cloning steps above but substitute the name of your server machine for localhost in the clone command above.  (This uses ssh for reading and writing to git.  You can find instructions out there for http if you’d rather use that.  I prefer ssh.)

You won’t need to use git add until there is at least one file you want git to know about.  Commits just let git understand that anything git knows you have changed is to be regarded as canon.

Add some files and make some changes. Then move into the project directory to add, commit, and push.

# move into some folder, probably called git, where you want to store your git repos
git clone yourusername@yourserver:/media/storage/.repos/project1
# now move into the newly cloned directory... 
cd project1
git add .
git commit -m "useful commit message so you remember what the fuck you did"
git push

If you set up a local copy on your server like I did above, you will want to regularly git pull into that copy so the files stored there are as up to date as possible (when you run your backups for example).

As near as I can tell this is the best way to manage that for oneself.  If there are better practices than those I’m using here, I’d like to see the detailed explanations for making them work and why they are a best practice.  Let me know.

Otherwise, have a great time with your newly minted git server.


Change Default Mail on Mac without Launching Mail

I clicked on a mailto link at work again.  Happens from time to time.  The Mac popped up Apple’s Mail as though that might help.  I kept meaning to change my default mail application; maybe today was the day?

Anyway, all of the instructions you will find tend to be, well, the same instructions:  open Mail, open Preferences, do some other stuff.  The trouble is that unless you set up a mail account in Mail you cannot open the Preferences.

Outlook used to have a setting for taking default, but that has gone away because Security!

Anyway, I found a solution (here) involving a small amount of Python which worked perfectly.  Nothing to install.  Just copy and paste and you’re good to go.  If you are not using Outlook, you’ll have to look up whatever the bundle identifier would be for your application of choice.  Here’s the code.

/usr/bin/python2.7 <<EOF
import LaunchServices;
result = LaunchServices.LSSetDefaultHandlerForURLScheme(
print("Result: %d (%s)" % (
    "Success" if result == 0 else "Error"))

(The use of EOF should allow you to copy and paste the entire block into a terminal without having to separately paste each line.)

Have fun with that!


Calculate Pi from Scratch

Having been inspired by a video by Matt from Stand-up Maths, I have written my first Python script.  You might be thinking “If this Matt guy is so smart, why is there an s on math?”.  I would of course feel obligated to attempt to explain how periodically English speakers attempt to re-Latinize words that may or may not have any connection with Latin, but that would really be taking us far afield.  Let’s concentrate on what really matters!

What really matters is that I have written my first Python script and I have put the first of my scripts on my GitHub repository for all to love.  Love it!

JamesIsIn / blech

Basically, the script (with some prompting from the user) rolls pairs of dice and seeks out whether those pairs are coprimes or not.  It that uses that data to calculate an estimate of pi.

You can watch Matt’s video here:

He studied in Australia how to be funny at math!  Success.


Powershellish Mailbox Creation

Found these old notes for making a post.  Figured I may as well move the notes here even if they are less relevant.  Maybe it will be useful to someone.

Mailbox Creation

Sometimes those old Exchange gui’s just ain’t enough. Time to bust out the command line. Here is some very useful information about doing just that.
So, of course, there is a special command prompt you will want to use: the Exchange Management Shell.

Main Data

I pulled this directly from the MS helps pages in Exchange. I did, however, add the very important (and neglected) identifier for each of these five mailbox types (at least my best guess):

User Account:

New-Mailbox -Name -Database -OrganizationalUnit -Password -UserPrincipalName [-ActiveSyncMailboxPolicy ] [-Alias ] [-DisplayName ] [-DomainController ] [-FirstName ] [-Initials ] [-LastName ] [-ManagedFolderMailboxPolicy ] [-ManagedFolderMailboxPolicyAllowed ] [-ResetPasswordOnNextLogon <$true | $false>] [-SamAccountName ] [-TemplateInstance ]

Linked Account:

New-Mailbox -Name -Database -LinkedDomainController -LinkedMasterAccount -OrganizationalUnit -UserPrincipalName [-ActiveSyncMailboxPolicy ] [-Alias ] [-DisplayName ] [-DomainController ] [-FirstName ] [-Initials ] [-LastName ] [-LinkedCredential ] [-ManagedFolderMailboxPolicy ] [-ManagedFolderMailboxPolicyAllowed ] [-Password ] [-ResetPasswordOnNextLogon <$true | $false>] [-SamAccountName ] [-TemplateInstance ]

Room Account:

New-Mailbox -Name -Database -OrganizationalUnit -Room -UserPrincipalName [-ActiveSyncMailboxPolicy ] [-Alias ] [-DisplayName ] [-DomainController ] [-FirstName ] [-Initials ] [-LastName ] [-ManagedFolderMailboxPolicy ] [-ManagedFolderMailboxPolicyAllowed ] [-Password ] [-ResetPasswordOnNextLogon <$true | $false>] [-SamAccountName ] [-TemplateInstance ]

Equipment Account:

New-Mailbox -Name -Database -Equipment -OrganizationalUnit -UserPrincipalName [-ActiveSyncMailboxPolicy ] [-Alias ] [-DisplayName ] [-DomainController ] [-FirstName ] [-Initials ] [-LastName ] [-ManagedFolderMailboxPolicy ] [-ManagedFolderMailboxPolicyAllowed ] [-Password ] [-ResetPasswordOnNextLogon <$true | $false>] [-SamAccountName ] [-TemplateInstance ]

Shared Account:

New-Mailbox -Name -Database -OrganizationalUnit -Shared -UserPrincipalName [-ActiveSyncMailboxPolicy ] [-Alias ] [-DisplayName ] [-DomainController ] [-FirstName ] [-Initials ] [-LastName ] [-ManagedFolderMailboxPolicy ] [-ManagedFolderMailboxPolicyAllowed ] [-Password ] [-ResetPasswordOnNextLogon <$true | $false>] [-SamAccountName ] [-TemplateInstance ]

Examples in Action

Create a shared mailbox:

new-Mailbox -alias testsharedmbx -name TestSharedMailbox -database "Mailbox Database" -org Users -shared -UserPrincipalName

Realworld example:

new-Mailbox -alias sanfrancisco -name SanFrancisco -database "Mailbox Database" -org "simplecompany.lan/simpleCOMPANY/Resource Accounts" -shared -UserPrincipalName sanfrancisco@simplecompany.lan


  • alias is the whatever@
  • name relates to the display name

Adding Permissions

Main Data

Add-MailboxPermission -Identity "Some User" -User DonaldK -Accessright Fullaccess -InheritanceType all

To this point everything is more or less clear but people find it hard to find more parameters for -Accessright, which is actually the most important part of the command. Here they are:

  • FullAccess
  • SendAs
  • ExternalAccount
  • DeleteItem
  • ReadPermission
  • ChangePermission
  • ChangeOwner

Examples in Action

Realworld example:

Add-MailboxPermission -Identity SanFrancisco -User "simpleCompany San Francisco ACL" -Accessright FullAccess -InheritanceType all

Mac Lock Screen Keyboard Shortcut(s)

The following is a method for creating a keyboard shortcut on a Mac such that the shortcut will lock the screen. This method involves using the Mac’s Automator and a bit of shell script. It is also important to set certain settings. We are going to show two different shortcut options. They can be run in parallel if desired. They also may be modified within reason and remain equally effective.

Launch Automator

  • From Automator choose File –> New –> Service which will open a new automation dialog
  • Here you have two (inclusive) options:
    • From the automation dialog select Utilities from the left-hand pane and then Run Shell Script
    • From the automation dialog select Utilities from the left-hand pane and then Start Screen Saver (pictured)
Utilities: Run or Start
Utilities: Run or Start
  • What’s the difference?
    • The shell script puts the system directly into the suspended state.
    • Suspending the system (via script) is slower but requires no additional settings.
    • Launching the screen saver does just that.
    • Launching the screen saver requires certain screen saver settings (below) and is faster.

The Automation (Two Options)

  • This is the line of code for you to copy and paste as below: /System/Library/CoreServices/Menu\ Extras/ -suspend
  • Again you will follow either the Run Shell Script path or the Start Screen Saver path:
    • Note the “no input” and the “any application” settings in both drop-downs for both methods below.

Via Shell Script (using Suspend):

  • Call the Run Shell Script something clear: LockViaSuspendShortcut
  • This is the line of code for you to copy and paste as above: /System/Library/CoreServices/Menu\ Extras/ -suspend
    • You will see the argument -switchToUserID for CGSession as well. This does not lock the screen. Do not use it.)
  • The Shell Script method (using suspend):
Lock via Script
Lock via Script

Via the Screen Saver:

  • … or Call the Start the Screen Saver something clear: LockViaScreenSaver
  • The Start the Screen Saver method:
Lock via Screen Saver
Lock via Screen Saver


  • If you need to delete an Automator Workflow, you can locate them in ~/Library/Services/
  • It may be possible to make an automation available to all users (untested) by placing it in /Library/Application Support/Apple/Automator/

Set Up the Keyboard Shortcut(s)

  • Once you have created these automations, you will only need to assign a shortcut for each.
  • Navigate to System Preferences –> Keyboard –> Shortcuts –> Services
  • Since you have used clear names per the above, you will have no difficulty identifying which automation is which.
  • The field to the right of the name of the automation holds the key combination.
  • Choose what you’d like and choose wisely.
    • LockViaScreenSaverShortcut is set as ctrl-alt-L
    • LockViaSuspendShortcut is set as shift-super-L
  • The mouse may need to be out of a VM in order for the shortcuts to be captured by the Mac.

Additional Screen Saver Settings

  • Open System Preferences –> Desktop & Screen Saver –> Screen Saver
  • Set “Start after:” as “5 Minutes
  • Open System Preferences –> Security & Privacy –> General
  • Set “Require password” as “5 seconds
    • These fives seconds will give you a small buffer to keep your screen from locking if you are reading an article and it goes blank.