0

For the following bash script

sudo -u root bash << EOF
FILE="defaults.txt"
if [ ! -e "$FILE" ]; then
    echo "min_granularity_ns" > $FILE
fi
EOF

I get this error:

bash: line 3: syntax error near unexpected token `newline'
bash: line 3: `    echo "min_granularity_ns" > '

Don't know what is wrong with that. If I use `echo "min_granularity_ns" > defaults.txt, there is no problem. How to fix that?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
mahmood
  • 23,197
  • 49
  • 147
  • 242
  • That link also mentions 'EOF' but if I saw that earlier, I wasn't able to link my problem to that. So, I think this should the topic should remain open. – mahmood Apr 17 '22 at 09:37
  • It doesn't need to remain open. The answers in the duplicate work and people will find them by reaching your question via Google. It's how this place works. –  Apr 17 '22 at 11:07

1 Answers1

2

Escape the $ to prevent the shell from expanding $FILE:

if [ ! -e "\$FILE" ]; then
    echo "min_granularity_ns" > \$FILE
fi

Note: This is not a great answer, but it does explain the problem: variable expansion before the here doc is created. So, I'm leaving it for now.

  • 1
    you don't need that, just use `'EOF'` instead of `EOF` to prevent variable substitution – phuclv Apr 17 '22 at 09:33
  • Tangentially, also quote `"\$FILE"`; see [When to wrap quotes around a shell variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Apr 19 '22 at 04:11