Polyglot shell script (sh, bat/batch, powershell)
I was slightly obsessed with polyglot files the last week; polyshell impressed me, but it bugged me that the BAT version printed "gibberish" on its first line. Could it be possible to get @ECHO OFF
working on the first line? After a couple of dead ends, I was able to make it work! See the source file.
The challenge is that the first character has to be @
, so PowerShell's try
cannot be set up (it doesn't have ||
). We also need to execute ECHO OFF
in Batch of course, and everything has to be valid syntax in all three languages, naturally.
The trick is to use PowerShell's hash table syntax; @{key=value}
. Output and errors are redirected to null
(both Shell and Cmd will complain about unknown command), and I added a couple of ||
to reset the return code/errorlevel.
For the rest of the file, I wanted to have some common code, and some interpreter specific code. I also wanted to try using less echo
and <<HEREDOC
than most scripts, just for fun. I ended up using if
, which exists in all languages.
Tested on PowerShell 2.0 and 7.1, Windows Cmd 6.1 and 10.0, Bash 3.2 and 5.0, and Dash.
Each language doesn't care what's inside a string or comment, let's replace those with _
:
@{a="\"} >$null # " 2>/dev/null || true #" >NUL 2>&1 || TYPE NUL & ECHO OFF
···········································································
PS @{a="_"} >$null #__________________________________________________________
Sh @{a="_____________" 2>/dev/null || true #__________________________________
Bat @{a="_"} >$null _ "______________________" >NUL 2>&1 || TYPE NUL & ECHO OFF
- Polyshell: Similar to this repo
- polyglot.bat: Bash/Bat file. Inspirational
GOTO
. - Batsh: A language that compiles to Bash and Windows Batch
- Hyperpolygot: Side-by-side command line interpreters reference
- SS64: Command line reference
- printimage.c: Bash/C file, I like
/*bin/echo '
:) - script.clj Clojure shell script
- Writing a Python/Ruby script