Jump to content

Shell 腳本

From Official NixOS Wiki
This page is a translated version of the page Shell scripts and the translation is 100% complete.

函數 writeShellScript 可用於向 Nix 表達式中添加 Shell 腳本。

someBuildHelper = { name, sha256 }:
  stdenv.mkDerivation {
    inherit name;
    outputHashMode = "recursive";
    outputHashAlgo = "sha256";
    outputHash = sha256;
    builder = writeShellScript "builder.sh" ''
      echo "hi, my name is ''${0}" # escape bash variable
      echo "hi, my hash is ${sha256}" # use nix variable
      echo "hello world" >output.txt
    '';
  };

外部 builder.sh 腳本

較長的 Bash 腳本通常會保存為外部腳本文件,並在 Nix 中調用:

❄︎ default.nix
{
  outputTxtDrv = stdenv.mkDerivation rec {
    name = "output.txt";
    # disable unpackPhase etc
    phases = "buildPhase";
    builder = ./builder.sh;
    nativeBuildInputs = [ coreutils jq ];
    PATH = lib.makeBinPath nativeBuildInputs;
    # only strings can be passed to builder
    someString = "hello";
    someNumber = builtins.toString 42;
    someJson = builtins.toJSON { dst = "world"; };
  };
}
≡︎ builder.sh
 jq -r '.dst') $someNumber" >$out

另見:

runCommand + builder.sh

除了使用 stdenv.mkDerivation 之外,還可以通過 runCommand 來調用外部的 Bash 腳本:

❄︎ default.nix
{
  outputTxtDrv = runCommand "output.txt" {
    nativeBuildInputs = [ coreutils jq ];
    # only strings can be passed to builder
    someString = "hello";
    someNumber = builtins.toString 42;
    someJson = builtins.toJSON { dst = "world"; };
  } (builtins.readFile ./builder.sh);
}

打包

示例:

# nix-build -E 'with import <nixpkgs> { }; callPackage ./default.nix { }'

{ stdenv
, lib
, fetchFromGitHub
, bash
, subversion
, makeWrapper
}:
  stdenv.mkDerivation {
    pname = "github-downloader";
    version = "08049f6";
    src = fetchFromGitHub {
      # https://github.com/Decad/github-downloader
      owner = "Decad";
      repo = "github-downloader";
      rev = "08049f6183e559a9a97b1d144c070a36118cca97";
      sha256 = "073jkky5svrb7hmbx3ycgzpb37hdap7nd9i0id5b5yxlcnf7930r";
    };
    buildInputs = [ bash subversion ];
    nativeBuildInputs = [ makeWrapper ];
    installPhase = ''
      mkdir -p $out/bin
      cp github-downloader.sh $out/bin/github-downloader.sh
      wrapProgram $out/bin/github-downloader.sh \
        --prefix PATH : ${lib.makeBinPath [ bash subversion ]}
    '';
  }

wrapProgram 會將原始腳本移動到 .github-downloader.sh-wrapped

命令未找到

例如,腳本會拋出錯誤 svn: command not found,這是因為缺少依賴包 subversion

當某個命令缺失時,可以使用 nix-locate 來查找對應的軟件包名稱。例如,stat 命令:

$ nix-locate bin/stat | grep 'bin/stat$'
coreutils.out       0 s /nix/store/vr96j3cxj75xsczl8pzrgsv1k57hcxyp-coreutils-8.31/bin/stat

調試嵌入腳本

當 Bash 腳本執行失敗時,它只會輸出錯誤信息,而不會顯示出錯的代碼位置。

要跟蹤命令和行號,可以使用

❄︎ test-trace.nix
{ runCommand, coreutils }:
runCommand "output.txt" { nativeBuildInputs = [ coreutils ]; } ''
  # line 5 in nix file = line 1 in bash script -> offset 4
  PS4='+ Line $(expr $LINENO + 4): '
  set -o xtrace # print commands

  echo hello >$out # line 9 in nix file

  set +o xtrace # hide commands
''
$ nix-build -E 'with import <nixpkgs> { }; callPackage ./test-trace.nix { }'
this derivation will be built:
  /nix/store/2v5biwny8plpyk2bv6cfr41ppp0a1i4k-output.txt.drv
building '/nix/store/2v5biwny8plpyk2bv6cfr41ppp0a1i4k-output.txt.drv'...
++ Line 9: echo hello
++ Line 11: set +o xtrace
/nix/store/ppidmnpd5m762x9kqj8jd3g7df7dknrz-output.txt

POSIX shell

某些環境(例如基於 BusyBox 的 OpenWRT)僅提供「受限」 Shell(使用 sh 而非 bash

在 NixOS 上,POSIX shells 由軟件包 dashposh 提供。

另見