Monday, April 1, 2019

Sha-Bang Your Scripts

Sometimes, Windows can be a friendly scripting environment. You write a batch file, and you run it. You write a Powershell script, and provided your Execution Policy allows it, you run it. If it is a batch file, you can even double-click it in the GUI. Powershell, however, you either need to run in its shell, or wrap it in a batch script. The bash shell works a bit differently.

The Sha-Bang (Sharp Bang) declares to the shell what is needed to execute the script. A bash script (example.sh) would normally look like:

#!/bin/sh
echo "Hello, World!"


You would then add the executable flag:

chmod +x example.sh

The same can be done with other interpreters, such as python or perl:

#!/usr/bin/env python
print("Hello, World!")


Or:

#!/usr/bin/perl -w
print "Hello, World!\n"


The same can be done with Powershell on linux, provided your shell knows where Powershell lives.

$ which powershell
/snap/bin/powershell


If you get a response, then Powershell is in your env PATH, so you can have:

#!/usr/bin/env powershell
Write-Host "Hello, World!"


Powershell users in Windows will note that just as running a local script, you need a dot-slash:

$ ./example.ps1
Hello, World!

No comments: