Shell Scripts: Difference between revisions
imported>Milahu + runCommand + builder.sh, fix links |
m Add category development and shell |
||
(5 intermediate revisions by 2 users not shown) | |||
Line 23: | Line 23: | ||
# default.nix | # default.nix | ||
{ | { | ||
outputTxtDrv = stdenv.mkDerivation rec { | |||
name = "output.txt"; | name = "output.txt"; | ||
# disable unpackPhase etc | # disable unpackPhase etc | ||
Line 55: | Line 55: | ||
# default.nix | # default.nix | ||
{ | { | ||
outputTxtDrv = runCommand "output.txt" { | |||
nativeBuildInputs = [ coreutils jq ]; | nativeBuildInputs = [ coreutils jq ]; | ||
# only strings can be passed to builder | # only strings can be passed to builder | ||
Line 97: | Line 97: | ||
--prefix PATH : ${lib.makeBinPath [ bash subversion ]} | --prefix PATH : ${lib.makeBinPath [ bash subversion ]} | ||
''; | ''; | ||
} | } | ||
</syntaxHighlight> | </syntaxHighlight> | ||
Line 111: | Line 111: | ||
$ nix-locate bin/stat | grep 'bin/stat$' | $ nix-locate bin/stat | grep 'bin/stat$' | ||
coreutils.out 0 s /nix/store/vr96j3cxj75xsczl8pzrgsv1k57hcxyp-coreutils-8.31/bin/stat | coreutils.out 0 s /nix/store/vr96j3cxj75xsczl8pzrgsv1k57hcxyp-coreutils-8.31/bin/stat | ||
</syntaxHighlight> | |||
== Debugging embedded scripts == | |||
When a bash script fails, it prints only an error message, but no code location. | |||
To trace commands and line numbers, we can use | |||
<syntaxHighlight lang="nix"> | |||
# 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 | |||
'' | |||
</syntaxHighlight> | |||
<syntaxHighlight lang="console"> | |||
$ 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 | |||
</syntaxHighlight> | </syntaxHighlight> | ||
Line 122: | Line 154: | ||
* [https://nixos.org/manual/nixpkgs/stable/#ssec-stdenv-functions Shell functions section in the Nixpkgs manual] | * [https://nixos.org/manual/nixpkgs/stable/#ssec-stdenv-functions Shell functions section in the Nixpkgs manual] | ||
* [https://gist.github.com/travisbhartwell/f972aab227306edfcfea nix-shell and Shebang Lines] | |||
* [https://ertt.ca/nix/shell-scripts/ Shell Scripts with Nix] | |||
[[Category:Development]] | |||
[[Category:Shell]] |