Bash create new file with content


How to BASH create a new file with content in Linux? In Bash scripting, there are multiple ways to use Bash create new file and populate it with content.

In this tutorial, we will explore three common methods to create a new file with content in Bash. You can use the commands line below

  • touch command to create an empty file: touch FILENAME
  • cat command to create a text file: cat > FILENAME

Write the contents to a file:
cat << “EOF” > /path/to/yourfilename
write the contents to a file
Use cat HERO DOCUMENT write content file

For example, My bash create new file with content.

I will create file jarservice in /etc/init.d/jarservice to java run jar as service on centos 6 as below.

# Author: HuuPV2
touch /etc/init.d/$yourservice

cat << "EOF" > /etc/init.d/$yourservice
case $1 in
     echo "Starting $SERVICE_NAME ..."
     if [ ! -f $PID_PATH_FILE ]; then
        nohup java -jar $PATH_TO_JAR >> $LOG_DIR 2>&1&
        echo $! > $PID_PATH_FILE
        echo "$SERVICE_NAME started ..."
        echo "$SERVICE_NAME is already running ..."
     if [ -f $PID_PATH_FILE ]; then
        PID=$(cat $PID_PATH_FILE);
        echo "$SERVICE_NAME stoping ..."
        kill $PID;
        echo "$SERVICE_NAME stopped ..."
        rm $PID_PATH_FILE
        echo "$SERVICE_NAME is not running ..."
     echo $"Usage: $0 {start|stop}"
     exit 2
chmod +x /etc/init.d/$yourservice
echo "Welcome to"

Run Bash create a new file with content

[huupv@huupv devopsroles]$ chmod +x 
[huupv@huupv devopsroles]$ sudo ./

The screen output terminal:

Bash create new file with content


Creating a new file with content in Bash is a straightforward task. By utilizing methods such as echo with output redirection, here documents, or printf with output redirection, you can generate files with ease.

Through the article, you can use Bash create new file with content as above. I hope will this your helpful. For more details refer to Bash script.

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.