Bash create new file with content

How to BASH create a new file with content in Linux? Bash script the essential for DevOps Roles. You can use commands 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
EOF

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.

#!/bin/bash
# Author: HuuPV2
yourservice=jarservice
touch /etc/init.d/$yourservice

cat << "EOF" > /etc/init.d/$yourservice
#!/bin/bash
SERVICE_NAME=$yourservice
PATH_TO_JAR=/path/to/yourapplication.jar
LOG_DIR=/var/log/yourapplication.log
PID_PATH_FILE=/var/run/yourapplication.pid
case $1 in
  start)
     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 ..."
     else
        echo "$SERVICE_NAME is already running ..."
     fi
     ;;
  stop)
     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
     else
        echo "$SERVICE_NAME is not running ..."
     fi
     ;;
     *)
     echo $"Usage: $0 {start|stop}"
     exit 2
esac 
EOF
chmod +x /etc/init.d/$yourservice
echo "Welcome to www.devopsroles.com"

Run Bash create a new file with content

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

The screen output terminal:

Bash create new file with content

Conclusion

Thought the article, you can use Bash create new file with content as above. I hope will this your helpful. 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 DevopsRoles.com 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.

Comment moderation is enabled. Your comment may take some time to appear.

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