0

I want to generate a bash file that could be called later, like this

cat <<-SCRIPT >test-$$
        #!/bin/bash
        osType=$(grep -Po '^NAME="\K[^"]*' /etc/os-release)
        if [ "$osType" = ...]
        then
            ...
        fi
        exit
    SCRIPT

while I am dubugging, the grep command always get execute right way, why? also try with awk same error

but if I do this

cat <<-SCRIPT >test-$$
        #!/bin/bash
        rpm -q somepackage > test-$$
        rm test-$$-lock
        exit
    SCRIPT

I don't see the rpm command get executed right way? Also does test-$$ and test-$$-lock will have the same $$?

4

A here-doc like <<-SCRIPT acts like a double-quoted string in that expansions are processed within it. To prevent that, quote the delimiter:

$ cat <<EOF
1+1 = $((1+1))
EOF

1+1 = 2

vs.

$ cat <<'EOF'
1+1 = $((1+1))
EOF

1+1 = $((1+1))

So, here:

cat <<-SCRIPT >test-$$
        ...
        osType=$(grep -Po '^NAME="\K[^"]*' /etc/os-release)

The grep command is within a command substitution which gets processed because SCRIPT is not quoted, so it is executed when the here-doc is used.

Here, on the other hand:

cat <<-SCRIPT >test-$$
        #!/bin/bash
        rpm -q somepackage > test-$$
        rm test-$$-lock
        exit
    SCRIPT

there's no command substitution, so no commands run. The rpm -q somepackage part is just text. However, with an unquoted delimiter, $$ inside the here-doc would be expanded immediately, to the same value used in the name of the output file. That is, if the current shell's PID is 1234, the cat command would create test-1234 containing the line rpm -q somepackage > test-1234.

With a quoted delimiter, the $$ would be left as-is, and the result would be file called test-1234 containing rpm -q somepackage > test-$$. If you now ran test-1234 as a script, the $$ would be expanded then, and that shell's PID would be used. It would probably be different from the value used when creating the file.

In any case, the $$ in rpm .. > test-$$ and rm test-$$-lock would get expanded to the same value.

| improve this answer | |
  • Thank you, can you help the follow up? – Tiger Sep 6 '19 at 17:57
  • @Tiger, all right, does that clarify? – ilkkachu Sep 6 '19 at 18:32
  • super! Thank you so much!!! – Tiger Sep 6 '19 at 18:48
  • +1 for pointing out different behaviors induced by quoting heredoc delimiters. – Cbhihe Sep 7 '19 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.