简体   繁体   English

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

[英]What is the proper way to make a bash script portable between Linux and FreeBSD?

I am working on some bash scripts that I'd like to work across my Linux and FreeBSD systems. 我正在研究一些我希望在我的Linux和FreeBSD系统上工作的bash脚本。

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 . 但这不适用于FreeBSD,因为bash位于/usr/local/bin/bash So on FreeBSD my scripts need to start with 所以在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. 我宁愿不维护两个版本的脚本。

#!/usr/bin/env bash

should do the trick, provided that bash is on the path somewhere. 应该这样做,只要bash在某个地方的路径上。 See here for more details. 有关详细信息,请参见此处

Honestly, if you want portability, invoke as /bin/sh and code to POSIX. 老实说,如果你想要可移植性,请调用/ bin / sh和代码到POSIX。 It's less pretty, but you will run into fewer potential issues if you do. 它不那么漂亮,但如果你这样做,你会遇到更少的潜在问题。

如果您想要便携式并且完全避免使用bashisms,请在两个系统上使用#!/bin/sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM