Monday, April 11, 2011

Cross platform shell script / batch file (Windows NT & Unix)

Here's a neat little hack I've come up with to script across both Windows and Unix.

It requires a ".bat" extension under Windows, and the execute bit set under Unix.

It uses the GOTO command in Windows to skip the Unix part, and it abuses the stderr redirect in Unix to effectively ignore the Windows IF and GOTO commands on line 1.


if %OS% == Windows_NT goto WINDOWS
then
:
## Hack to make a cross-OS compatible script
fi 2> /dev/null

# ------------------------------------------------------------------------------
# Unix execution
# ------------------------------------------------------------------------------

NAME=$0
NAME=${NAME%.bat}
NAME=${NAME##*/}

echo "My name is ${NAME}, and I work in Unix environments"

exit

# ------------------------------------------------------------------------------
# Windows execution
# ------------------------------------------------------------------------------

:WINDOWS
@echo off

set NAME=%~n0

echo My name is %NAME%, and I work in Windows NT environments"

# ------------------------------------------------------------------------------