Using > and variable file name

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?

>Solution :

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

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

Leave a Reply