Home > Software design >  bash command cat doesn't work inside an if statement
bash command cat doesn't work inside an if statement

Time:04-05

I can create a file with content using a bash script with the cat command like so:

#!/bin/sh

cat >myFyle.txt <<EOL
Some text inside the file
EOL

This works as intended. But when I try to use this inside an if statement like so:

#!/bin/sh

if true; then
    cat >myFyle.txt <<EOL
    Some text inside the file
    EOL
fi

I get the error message:

Syntax error: end of file unexpected (expecting "fi")

Why does this not work and how do I use cat correctly inside an if statement?

Note: The condition for the if statement is exemplary. This is just to ensure that the example executes the code.

CodePudding user response:

The ending delimiter line has to exactly EOL. No spaces in front.

if true; then
    cat >myFyle.txt <<EOL
    Some text inside the file
EOL
#^^^ Spaces above will be preserved!
fi

You can use <<-EOL and then use a tab (not spaces!) in front, which will be ignored.

if true; then
    cat >myFyle.txt <<-EOL
    Some text inside the file
    EOL
#^^^ - This is a tab. Tabs in front will be ignored.
fi
  • Related