在Linux和FreeBSD之间移植bash脚本的正确方法是什么?

时间:2021-02-22 21:33:13

I am working on some bash scripts that I'd like to work across my Linux and FreeBSD systems.

我正在开发一些bash脚本,我想在我的Linux和FreeBSD系统上使用这些脚本。

Since I mostly work in Linux, I am used to starting my bash scripts with

由于我主要在Linux中工作,所以我习惯于使用bash脚本

#!/bin/bash

But this doesn't work on FreeBSD since bash lives at /usr/local/bin/bash. So on FreeBSD my scripts need to start with

但是这在FreeBSD上不起作用,因为bash位于/usr/local/bin/bash所以在FreeBSD,我的脚本需要开始

#!/usr/local/bin/bash

So is there something else I could use that would be portable across both systems? I'd rather not maintain two versions of the scripts.

那么我还可以用什么东西在两个系统中都是可移植的呢?我宁愿不维护两个版本的脚本。

3 个解决方案

#1


16  

#!/usr/bin/env bash

should do the trick, provided that bash is on the path somewhere. See here for more details.

应该这样做,前提是bash位于某个路径上。详情请参见这里。

#2


6  

Honestly, if you want portability, invoke as /bin/sh and code to POSIX. It's less pretty, but you will run into fewer potential issues if you do.

坦白地说,如果您想要可移植性,请将其调用为/bin/sh和代码到POSIX。它不那么漂亮,但如果你这样做,你会遇到更少的潜在问题。

#3


2  

Use #!/bin/sh on both systems if you want to be portable and avoid bashisms entirely.

使用# !如果你想要随身携带并且完全避免bashisms,那么在这两个系统上都可以使用。

#1


16  

#!/usr/bin/env bash

should do the trick, provided that bash is on the path somewhere. See here for more details.

应该这样做,前提是bash位于某个路径上。详情请参见这里。

#2


6  

Honestly, if you want portability, invoke as /bin/sh and code to POSIX. It's less pretty, but you will run into fewer potential issues if you do.

坦白地说,如果您想要可移植性,请将其调用为/bin/sh和代码到POSIX。它不那么漂亮,但如果你这样做,你会遇到更少的潜在问题。

#3


2  

Use #!/bin/sh on both systems if you want to be portable and avoid bashisms entirely.

使用# !如果你想要随身携带并且完全避免bashisms,那么在这两个系统上都可以使用。