Skip to content

Polyglot shell script (sh, bat/batch, powershell)

Notifications You must be signed in to change notification settings

tingstad/polyscript

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

polyscript

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.

Polyscript on Windows

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.

Explanation

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

Links

About

Polyglot shell script (sh, bat/batch, powershell)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published