According to this NixOs Cookbook recipe I’ve tried to write a custom bash script.
The original script is working well on Debian, but caused an error in NixOS if I try to rebuild the NixOS system.
Script:
{ pkgs, ... }:
let
testscript = pkgs.writeScriptBin "testscript" ''
#!${pkgs.stdenv.shell}
sleep 1
KEYBOARD_MASTER_DEV_ID=$(xinput | grep -oP 'Virtual core keyboard\s+id=\K[0-9]+(?=.+master\s+keyboard)')
if [[ -n ${KEYBOARD_MASTER_DEV_ID} ]]; then
setxkbmap -device ${KEYBOARD_MASTER_DEV_ID} en
fi
'';
in {
environment.systemPackages = [ testscript ];
}
NixOS builder reports an “undefined variable” at this line of code if [[ -n ${KEYBOARD_MASTER_DEV_ID} ]]; then
Can anybody give me a hint, what’s wrong with my nix file, please?
Yeah, what’s happening here is the ${KEYBOARD_MASTER_DEV_ID} is a Nix language construct that tries to expand a Nix variable with the name KEYBOARD_MASTER_DEV_ID into the string. Since you want the ${} to go through verbatim to the bash script, you’ll need to escape the variable expansion with two leading single quotes: ''${KEYBOARD_MASTER_DEV_ID}
As already noted by the other posters, you have to escape ${} with ''${} to protect it from expansion in Nix. Furthermore writeScriptBin is actually the wrong function to create shell script. It should be writeShellScriptBin which automatically add the correct shell and checks the syntax. (I’ve updated the Wiki accordingly)
{ pkgs, ... }:
let
testscript = pkgs.writeShellScriptBin "testscript" ''
sleep 1
KEYBOARD_MASTER_DEV_ID=$(xinput | grep -oP 'Virtual core keyboard\s+id=\K[0-9]+(?=.+master\s+keyboard)')
if [[ -n ''${KEYBOARD_MASTER_DEV_ID} ]]; then
setxkbmap -device ''${KEYBOARD_MASTER_DEV_ID} en
fi
'';
in {
environment.systemPackages = [ testscript ];
}