Writing Scripts in Nix
Create executible shell script
writeShellScriptBin
# custom-script.nix
{ pkgs, config, ...}:
let
custom_script = pkgs.writeShellScriptBin "script_name" ''
function() {
if [ -n "$1" ] ; then
echo $1
fi
}
'';
in {
home = {
packages = with pkgs;
[
custom_script
other_packages
];
};
}
which script_name
outputs /home/dave/.nix-profile/bin/pwgen
from your $PATH
programs.bash.shellInitBash Initialization
Alternatively with NixOS programs.bash.shellInit
or HomeManager programs.bash.
as follows placing it in shellInitinitExtra.bashrc
:
## custom-script.nix
programs = {
bash = {
## shellInit = ''
initExtra = ''
function() {
if [ -n "$1" ] ; then
echo $1
fi
}
'';
};
};
Parameter Expansion
When porting bash scripts into nix files either and wanting to use bash expansion eg ${variable:0:1}
make sure you escape the characters, otherwise it will be read literally upon rebuild and fail.
Don't do this:
variable=value
echo ${value^^}
error: syntax error, unexpected invalid token, expecting '}'
Do this instead:
variable=value
echo ''${value^^}