How to Get a Bash Script Working on Freebsd, Openbsd and Linux Without Modifying It

How do I get a bash script working on FreeBSD, OpenBSD and Linux without modifying it?

Using env in the shebang (#!/usr/bin/env bash) should make the script OS agnostic.

Unix and FreeBSD

OpenBSD, FreeBSD, DragonFlyBSD, NetBSD, Open Solaris, etc. are all open and free Unix operating systems, you cannot really get closer than that.

To circumvent the installation restriction consider virtualization with a tool like Sun's Virtual box.

How to get prefix-set working in Openbgpd config

Turns out I was looking at https://man.openbsd.org/bgpd.conf while I should have been looking at the docs from https://www.freebsd.org/cgi/man.cgi?query=bgpd.conf as per Richard Smith's reply.

prefix-set is not a thing in FreeBSD bgpd

How to check if running in Cygwin, Mac or Linux?

Usually, uname with its various options will tell you what environment you're running in:

pax> uname -a
CYGWIN_NT-5.1 IBM-L3F3936 1.5.25(0.156/4/2) 2008-06-12 19:34 i686 Cygwin

pax> uname -s
CYGWIN_NT-5.1

And, according to the very helpful schot (in the comments), uname -s gives Darwin for OSX and Linux for Linux, while my Cygwin gives CYGWIN_NT-5.1. But you may have to experiment with all sorts of different versions.

So the bash code to do such a check would be along the lines of:

unameOut="$(uname -s)"
case "${unameOut}" in
Linux*) machine=Linux;;
Darwin*) machine=Mac;;
CYGWIN*) machine=Cygwin;;
MINGW*) machine=MinGw;;
*) machine="UNKNOWN:${unameOut}"
esac
echo ${machine}

Note that I'm assuming here that you're actually running within CygWin (the bash shell of it) so paths should already be correctly set up. As one commenter notes, you can run the bash program, passing the script, from cmd itself and this may result in the paths not being set up as needed.

If you are doing that, it's your responsibility to ensure the correct executables (i.e., the CygWin ones) are being called, possibly by modifying the path beforehand or fully specifying the executable locations (e.g., /c/cygwin/bin/uname).

Why can a script with a #!/bin/sh shebang use bash-only features?

/bin/sh is a link to your actual shell. It does not mean that you are running pure POSIX. The Git for windows homepage makes very clear that you are running bash, as does your git-bash tag.

Even on Linux, /bin/sh can still be bash:

ls -la /bin/sh
lrwxrwxrwx. 1 root root 4 Mar 27 09:33 /bin/sh -> bash

How to resolve symbolic links in a shell script

According to the standards, pwd -P should return the path with symlinks resolved.

C function char *getcwd(char *buf, size_t size) from unistd.h should have the same behaviour.

getcwd
pwd



Related Topics



Leave a reply



Submit