minishell icon indicating copy to clipboard operation
minishell copied to clipboard

[KNOWN ISSUE] Word splitting and filename expansion should not be performed when assigning values to variables

Open itislu opened this issue 1 year ago • 0 comments

Definition:

name=[value]

Test case:

bash-5.1$ export A="  a  b  c  "
bash-5.1$ export Z=$A
bash-5.1$ export

Result:

export Z="  a  b  c  "

Reminder what word splitting usually does:

bash-5.1$ export $A
bash-5.1$ export
.
.
.
export a
export b
export c

Reference: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/html_node/Shell-Parameters.html


Explanation

[!NOTE] Thanks a lot to @gwolf-011235! The following is directly quoted from him.

Bash has flags for its builtins, one of which is "ASSIGNMENT_BUILTIN", which indicates "This builtin takes assignment statements." - builtins.h

This flag is checked in function fix_assignment_words() which has the amusing description: "This is a hack to suppress word splitting for assignment statements given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set." - execute_cmd.c

This function is called in execute_simple_command() before the words get expanded with expand_words() - execute_cmd.c

If you hide export from bash before expansion takes place you can achieve the result you were expecting:

export A="  a  b  c  "
sneaky_boy=export
$sneaky_boy Z=$A

gives you

[...]
export Z=""
export a
export b
export c

itislu avatar Mar 31 '24 22:03 itislu