Search code examples
bashaliaseol

Bash alias or function to create multiline file


I have the following bash command that creates a multiline file in the current directory:

cat > data.txt <<EOL
Line 1
Another line
Something else
EOL

I'm trying to create a bash alias or function to run this command. I've tried the following but nothing happens:

alias create-file="
cat > ~/Desktop/stuffs/data.txt <<EOL
Line 1
Hello world
Another line
EOL"

No luck trying the funciton either:

function npmrcpersonal() {
  "cat > ~/Desktop/stuffs/data.txt <<EOL
  Line 1
  Hello world
  Another line
  EOL"
}

What am I doing wrong here?


Solution

  • You don't quote the body of a function. And the here-doc shouldn't be indented.

    function npmrcpersonal() {
      cat > ~/Desktop/stuffs/data.txt <<EOL
    Line 1
    Hello world
    Another line
    EOL
    }
    

    The EOL marker will only be recognized if it's at the left margin (unless you use <<-EOL, then it's allowed to be indented, but only with TAB characters, not spaces). The rest of the here-doc shouldn't be indented because those spaces will go into the file, and you probably don't want that.