Skip to content

Minifying heredoc values in command substitutions produces invalid shell #923

Closed

Description

@andreykaipov

For example, running the following file through shfmt -mn:

#!/bin/sh
a=$(
        cat <<EOF
	hello
EOF
)
echo "$a"

Produces the following shell:

#!/bin/sh
a=$(cat \
<<EOF)
	hello
EOF
echo "$a"

Which can't be ran:

sh: line 4: warning: here-document at line 4 delimited by end-of-file (wanted `EOF')
sh: line 3: warning: here-document at line 3 delimited by end-of-file (wanted `EOF')
sh: line 4: hello: command not found
sh: line 5: EOF: command not found

For some context, I'm using this kind of pattern to assign literal strings to a variable. I can use something like read -r -d '' a <<'EOF' in bash, but afaik assigning cat <<'EOF' is the way to do something like that with posix sh.

Activity

  1. andreykaipov commented on Oct 2, 2022

    @andreykaipov
    ContributorAuthor

    So this behavior is actually not just with command substitutions, but also exists for heredocs in subshells and in process substitutions too.

  2. andreykaipov commented on Oct 2, 2022

    @andreykaipov
    ContributorAuthor

    Digging through the code I've at least figured a workaround:

    #!/bin/sh
    a=$(
            cat <<EOF
    	hello
    EOF
            :
    )
    echo "$a"
    

    Adding an extra statement after the ending heredoc word allows the formatter to correctly flush the heredoc, I'm guessing because of the new line. Now running shfmt -mn produces:

    #!/bin/sh
    a=$(cat \
    <<EOF
            hello
    EOF
    :)
    echo "$a"
    
  3. added a commit that references this issue on May 9, 2023
    639c8b3
  4. added a commit that references this issue on Jul 7, 2024
    ca2088c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ 换网址