toShellVar
lib.strings.toShellVar
Docs pulled from | This Revision | about 3 hours ago
Translate a Nix value into a shell variable declaration, with proper escaping.
The value can be a string (mapped to a regular variable), a list of strings (mapped to a Bash-style array) or an attribute set of strings (mapped to a Bash-style associative array). Note that "string" includes string-coercible values like paths or derivations.
Strings are translated into POSIX sh-compatible code; lists and attribute sets assume a shell that understands Bash syntax (e.g. Bash or ZSH).
Inputs
name
- 1. Function argument
value
- 2. Function argument
Type
string -> ( string | [string] | { ${name} :: string; } ) -> string
Examples
lib.strings.toShellVar
usage example
''
${toShellVar "foo" "some string"}
[[ "$foo" == "some string" ]]
''
Noogle detected
Implementation
The following is the current implementation of this function.
toShellVar = name: value:
lib.throwIfNot (isValidPosixName name) "toShellVar: ${name} is not a valid shell variable name" (
if isAttrs value && ! isStringLike value then
"declare -A ${name}=(${
concatStringsSep " " (lib.mapAttrsToList (n: v:
"[${escapeShellArg n}]=${escapeShellArg v}"
) value)
})"
else if isList value then
"declare -a ${name}=(${escapeShellArgs value})"
else
"${name}=${escapeShellArg value}"
);