Creating a file with some content in Shell scripting

  • I'm a little new to Shell Scripting and I want to create a new file inside the script and want to add content and then close it. It should not take the arguments from the user. Everything from the path and content is predefined. How can I do it?

  • gertvdijk

    gertvdijk Correct answer

    7 years ago

    Just use output redirection. E.g.

    #!/bin/bash
    
    echo "some file content" > /path/to/outputfile
    

    The > will write all stdin provided by the stdout of echo to the file outputfile here.

    Alternatively, you could also use tee and a pipe for this. E.g.

    echo "some file content" | tee outputfile
    

    Be aware that any of the examples will overwrite an existing outputfile.

    If you need to append to a currently existing file, use >> instead of > or tee -a.

    If you don't accept user input in this line, no user input can change the behaviour here.

    For people who want to have a line breaker inside their file, see here: https://stackoverflow.com/a/9741470/10512595

  • I think it is superior to use a here doc to create a new file in a script. It is cleaner looking, which I believe encourages readability.

    For example:

    cat > filename <<- "EOF"
    file contents
    more contents
    EOF
    

    The "-" in <<- is optional, allowing for tabbed indents which will be stripped when the file is created. The quotes around the "EOF" prevent the "here doc" from doing any substitutions.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM