DEV Community

cryptocode
cryptocode

Posted on • Updated on

Who needs a #! anyway

Look at this beauty:

//usr/bin/env zig run $0 $@ ; exit 
const std = @import("std");
pub fn main() !void {
    std.log.info("Awesome, it works\n", .{});
}
Enter fullscreen mode Exit fullscreen mode

Let's make it executable and run it:

chmod +x myscript.zig

./myscript.zig
info: Awesome, it works
Enter fullscreen mode Exit fullscreen mode

This works because // is a comment in zig and the first line is a executed by the shell.

Discussion (4)

Collapse
ifreund profile image
Isaac Freund

Nice trick! note that this will only work in some shells such as bash. If you pass the zig source file directly to the kernel as the argument of execve() the kernel won't run it sadly as it only understands #!/path.

Collapse
stein profile image
cryptocode Author

Yeah, good point. Also works nicely in zsh, so I think it'll work for a lot of people.

Collapse
heavyrain266 profile image
HeavyRain266

Also works nicely in all type of kernshells such as mksh, also in busybox ash and more :)

Thread Thread
stein profile image
cryptocode Author

That's awesome - thanks!