0

I'm trying to get PID of command executed inside EOF block.

$ bash << EOF

> sleep 10 &
> pid1=$!
>
> sleep 10 &
> pid2=$!
>
> echo "ID1: $pid1 --- ID2: $pid2"
> EOF

In this case variables with pids are empty.

ID1:  --- ID2: 

Is there a way to get pids for such scenario?

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
Pavel
  • 141
  • 1
  • 3
  • 10

1 Answers1

2

Here-document content is expanded by the shell you are typing your characters into. Prevent the expansion of the parent shell, either by escaping or quoting the here-document delimiter.

$ bash <<EOF
sleep 10 &
pid1=\$!
sleep 10 &
pid2=\$!
echo "ID1: \$pid1 --- ID2: \$pid2"
EOF

$ bash <<'EOF'
sleep 10 &
pid1=$!
sleep 10 &
pid2=$!
echo "ID1: $pid1 --- ID2: $pid2"
EOF
KamilCuk
  • 120,984
  • 8
  • 59
  • 111