loading...

Writing cross platform scripts with Sparrow6

melezhik profile image Alexey Melezhik ・2 min read

With the recent changes Sparrow6 allows to create scripts compatible with Windows and Linux.

Why one would need that?

In my daily $work I create a lot of scripts saving my time. The challenge is that I often switch between Linux and Windows environments.
Having bunch of scripts working say for Linux, does automatically mean they would work for Windows. So I'd end up rewriting a code from the scratch which take a lot of time or would I?

Why not bring this cross platform feature into initial design and write scripts compatible for both systems?

With Sparrow6 it's really piece of cake.


Hello Linux/Windows on Sparrow6

Let's create a simple script that just print Hello World, but have it to do for both Linux and Windows.

Linux version:

tasks/hello/linux/task.bash

echo "Hello world, $(config name)"

We base on that fact that Bash is a standard Linux shell available on most Linux systems.

Windows version:

tasks/hello/windows/task.ps1

Write-Host "Hello world, $(config name)"

We again base on the fact that Powershell is a standard Windows shell available on most Windows system.

These examples are too simple, but in real life you'd write more complicated scripts. I just only want to emphasize that you'd choose proper shell depending on your system. Bash or Powershell

Script switch

Sparrow6 is good at glueing things together and at orchestrating scripts. We just need a little hook, written on Perl6 to run our scripts conditionally on operating system:

hook.pl6

#!perl6

if os() eq 'windows' {
    run_task "hello/windows"
} else {
    run_task "hello/linux"
}

So we end up with a small Sparrow6 plugin we could run:

$ tree .

.
├── hook.pl6
└── tasks
    └── hello
        ├── linux
        │   └── task.bash
        └── windows
            └── task.ps1

4 directories, 3 files

On my Linux box it would be:

perl6 -MSparrow6::DSL -e 'task-run(".", %( name => "Raku" ))'

02:32:16 09/25/2019 [.] Hello world, Raku

Thank you for reading. If you want flexible and no fuss automation try out Sparrow - the tool I use in my daily work.

Comments, questions, ideas as always are welcome.

Discussion

pic
Editor guide