Writing alias scripts for UNIX and Windows


I recently stumbled upon a problem where I needed to write aliases for an executable binary, without knowing its absolute path in advance, and do so in both UNIX (macOS and GNU/Linux) and Windows. Distributing symbolic links was not an ideal approach as they are not easy to handle correctly in various compressed formats.

After some research, I came up with the following shell scripts and thought it might be useful to document them in a central place. Lets assume our program is called foobar, and the alias is a sibling file.

In the case of Windows, we easily write this in Batch and store it in a .cmd file:

@echo off
call "%~dp0\foobar.exe" %*
exit /b %ERRORLEVEL%

The %~dp0 expression evaluates to the directory the script lives in, and %* evaluates to all the arguments passed to the script. Finally, we make sure we exit the alias script with the same exit code as the executed program. The .cmd extension ensures we can execute this script from the file manager, and also from the terminal, even when omitting the extension.

The UNIX script is trickier if we want to be compatible with any POSIX shell, and don’t depend on GNU extensions such as readlink -f:

#!/bin/sh

TARGET_FILE="$0"

set -ei

cd "$(dirname "$TARGET_FILE")"
TARGET_FILE="$(basename "$TARGET_FILE")"

while [ -L "$TARGET_FILE" ]
do
  TARGET_FILE="$(readlink "$TARGET_FILE")"
  cd "$(dirname "$TARGET_FILE")"
  TARGET_FILE="$(basename "$TARGET_FILE")"
done

SCRIPT="$(pwd -P)/$TARGET_FILE"
SCRIPTPATH=$(dirname "$SCRIPT")

"$SCRIPTPATH/foobar" $*

The $SCRIPTPATH variable contains the source directory of the script (like %~dp0). All the code above it pretty much simulates readlink -f on non-GNU systems, $* evaluates to all arguments passed to the script, and set -e ensures we exit the alias script with the program exit code.

References