Learning New Old Tricks

Sometimes, you discover something, that others have known for a long time. Last week, I've discovered how useful a ~/bin directory can be.

Linux

After creating a ~/bin directory on my Ubuntu machine, the directory is already part of the PATH variable. Any executable or script put in the ~/bin directory can be turned into a global available command after changing permissions and reloading the profile:

mkdir ~/bin
cp /path/to/script ~/bin
chmod +x ~/bin/script
. ~/.profile

Windows

I had to manually add ~/bin to the PATH variable:

$homeBinDir = Join-Path $env:USERPROFILE 'bin'
New-Item $homeBinDir -ItemType Directory -Force | Out-Null
[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';' + $homeBinDir, 'User')

Windows uses two different shells: cmd.exe and powershell.exe. You can use .bat, .cmd and .ps1 scripts in PowerShell, but you cannot use .ps1 in Cmd. Because of this, I've written a simple "wrapper script" which I can use to make a .ps1 script available in Cmd:

@ECHO OFF
PowerShell.exe -NoProfile -File "%~dpn0.ps1"

This .cmd script will call a .ps1 with the same name (e.g. foo.cmd will call foo.ps1). Such a script can also be used to start a .ps1 script as an Administrator in a new process:

@ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"

Running foo in:

  • a Cmd session will execute foo.cmd
  • a PowerShell session will execute foo.ps1 (or foo.cmd if foo.ps1 cannot be found)

Usage Examples

So we've got our bin directory set up, now what? Well, here's a short list of scripts which I'm using on my machines:

  • my-pull: Calls git pull on a bunch of different repositories. This makes it easy to download changes across several projects
  • my-rsync: A custom "backup" script which relies on rsync to copy a snapshot of several directories to an external drive
  • my-robo: Same as above, but using robocopy.exe on Windows
  • my-restic: An experimental (real backup) script which uses restic
  • homebank-import: A script which transforms CSV export files from my bank to a CSV format which I can import in homebank

Published: 2019-07-06