mcandre
mcandre

Reputation: 24602

How to write a modulino in zsh?

I like to write my scripts as "modulinos", shell scripts that can be called by themselves as little CLI programs, or imported by other programs as libraries.

I can do this in bash with:

https://github.com/mcandre/scriptedmain/tree/master/bash

And I would like to do this in zsh as well. How could I do this?

The most important thing is to find a way to emulate bash's:

if [[ "$BASH_SOURCE" == "$0" ]]
then
    main
fi

In other words, find the name of this script vs the name of the summoned program (when they're equal, run main(), when they're different, skip, because this script is being imported as a library).

The trouble is, I think zsh's $0 behaves like bash's $BASH_SOURCE, and I don't think there's a zsh equivalent to bash's $0 (which works differently) to compensate.

Upvotes: 1

Views: 99

Answers (1)

chepner
chepner

Reputation: 531135

Check the value of the last element of zsh_eval_context. If it equals "toplevel", that should be equivalent to the $BASH_SOURCE == $0 check being true.

if [[ $zsh_eval_context[-1] == toplevel ]]; then
    main
fi 

Upvotes: 1

Related Questions