Ansible playbook NGINX + PHP

In this tutorial, I will deploy  Ansible playbook Nginx and PHP for remote server centos 7. Ansible the essential for DevOps Roles.

My system:

Control server: DevopsRoles —–> Remote server: webserver

Control server:

Installed Ansible “I use root account running Ansible, You are understand? Please careful

Remote server:

  •  Install webserver Nginx and PHP
  •  Create a user huupv with sudo privileges ( more details ref to linux create user )

Ansible playbook NGINX + PHP

Create a folder and file for Ansible Nginx

[root@DevopsRoles ~]# pwd
/root
[root@DevopsRoles ~]# mkdir ansible-nginx
[root@DevopsRoles ~]# mkdir ansible-nginx/inventory
[root@DevopsRoles ~]# vi ansible-nginx/webserver-main.yml

The content  webserver-main.yml file as below

- name: install and configure the web server
  hosts: webserver
  remote_user: huupv
  become: yes

  roles:
    - nginx
    - php

Create file hosts

[root@DevopsRoles ~]# vi ansible-nginx/inventory/hosts

The content is as below:

[webserver]
192.168.1.113

In this command, checking for communication use the ping module ansible.

[root@DevopsRoles ansible-nginx]# ansible all -i inventory/hosts -m ping

192.168.1.113 | SUCCESS => {
"changed": false, 
"ping": "pong"
}

Ansible roles Nginx and PHP

[root@DevopsRoles ~]# mkdir ansible-nginx/roles
[root@DevopsRoles ~]# cd ansible-nginx/roles
[root@DevopsRoles roles]#

create the role for Nginx and PHP. Using ansible-galaxy creates a template

[root@DevopsRoles roles]# ansible-galaxy init nginx
- nginx was created successfully
[root@DevopsRoles roles]# ansible-galaxy init php
- php was created successfully

Ansible roles Nginx create by ansible-galaxy

Ansible structure folder and file as below

nginx
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
└── main.yml

8 directories, 8 files

Setting ansible task Nginx

The modify nginx/tasks/main.yml for role Nginx

[root@DevopsRoles roles]# vi nginx/tasks/main.yml

The content main.yml file as below

# tasks file for nginx
- name: Install NGINX.
  yum: name=nginx
- command: chkconfig nginx on
- command: service nginx restart
- name: Install NGINX.
  yum: name={{ item }}
  with_items:
    - http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm

  # enabled=0
  - replace: dest=/etc/yum.repos.d/{{ item }} regexp="enabled *= *1" replace="enabled=0"
  with_items:
     - nginx.repo
  - yum: name=nginx
  - command: chkconfig nginx on
  - command: service nginx restart

Ansible roles PHP create by ansible-galaxy

Ansible structure folder and file as below

php
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
└── main.yml

8 directories, 8 files

Setting ansible task PHP

The Modify php/tasks/main.yml for role PHP

[root@DevopsRoles roles]# vi php/tasks/main.yml

The content is as below:

# tasks file for php
- name: Install PHP
  yum: name={{ item }} state=present enablerepo=epel
  with_items:
   - php70u-cli
   - php70u-common
   - php70u-fpm
   - php70u-fpm-nginx
   - php70u-json
   - php70u-mysqlnd
   - php70u-opcache
   - php70u-pdo

Ansible tasks/main.yml installed modules of PHP from yum in succession. Convenient!

Run ansible playbook

Run check the syntax of the Ansible playbook

[root@DevopsRoles ansible-nginx]# ansible-playbook -C -i inventory/hosts webserver-main.yml

Checking result syntax ok run ansible-playbook again

[root@DevopsRoles ansible-nginx]# ansible-playbook -i inventory/hosts webserver-main.yml

The confirm installed Nginx and PHP on a host web server

Nginx version

PHP version

Remember to customize the playbook and PHP-FPM configuration based on your specific requirements.

Conclusion

Through the article, you can use the Ansible playbook NGINX + PHP as above. I hope will this your helpful. For more details refer to the Ansible tutorial.

Ansible tutorial beginners

In this article, I will guide Ansible tutorial beginners. How to create ansible playbook? Ansible the essential for DevOps Roles.

  1. What is Ansible
  2. Ansible best practices

The environment for my system as below

[root@DevopsRoles ~]# ansible --version
ansible 2.6.2
[root@DevopsRoles ~]# python --version
Python 2.7.5

Server01: Control Machine 

  • VM01: DevopsRoles (Installed Ansible)
  • IP: 192.168.1.112

Server02: Target

  • VM02: a web server
  • IP: 192.168.1.113

What is Ansible

Introduction to Infrastructure as Code by Ansible.

“Ansible is the simplest way to automate apps and IT infrastructure. Application Deployment + Configuration Management + Continuous Delivery”

Here’s a beginner-friendly Ansible tutorial to get you started:

Ansible tutorial best practices

Installation of Ansible

Guide install Ansible on Centos/Ubuntu/Redora

Step by step for Ansible

Create the folder for Ansible

[root@DevopsRoles ~]# mkdir ansible
[root@DevopsRoles ~]# mkdir ansible/{inventory,group_vars,files,templates}

Create files for Ansible

[root@DevopsRoles ~]# pwd
/root
[root@DevopsRoles ~]# touch ansible/inventory/hosts
[root@DevopsRoles ~]# touch ansible/group_vars/webserver.yml
[root@DevopsRoles ~]# touch ansible/files/file_webserver
[root@DevopsRoles ~]# touch ansible/templates/template_webserver.j2
[root@DevopsRoles ~]# touch ansible/test_ansible.yml
[root@DevopsRoles ~]# touch ansible/main.yml

Ansible structure folder and file as below

ansible/
├── files
│   └── file_webserver
├── group_vars
│   └── webserver.yml
├── inventory
│   └── hosts
├── main.yml
├── templates
│   └── template_webserver.j2
├── test_ansible.retry
└── test_ansible.yml

To create ssh-keygen from VM01 DevopsRoles communication to VM02 webserver do not enter the password.

[root@DevopsRoles ~]# ssh-keygen -t rsa
[root@DevopsRoles ~]# ssh-copy-id root@192.168.1.113

The terminal output as below

I’m running Ansible playbook as root, I guess you understand. Please be careful.

In this inventory file, we have a host named 192.168.1.113 in the group “[webserver]” (VM02).

[webserver]
192.168.1.113

In this command, checking for communication use the ping module ansible.

[root@controller ansible] ansible all -i inventory/hosts -m ping

The terminal output as below

[root@DevopsRoles ansible]# ansible all -i inventory/hosts -m ping
192.168.1.113 | SUCCESS => {
"changed": false, 
"ping": "pong"
}

Create Ansible playbook

To create a webserver.yml file.

[root@DevopsRoles ansible]#  cat group_vars/webserver.yml

---
message: "Hello Ansible !" 
Info: 
   huu: 
     age: 29 
   songoku: 
     age: 100 
   laika: 
     age: 30

This file describes group variables. To create a test_ansible.yml file

[root@DevopsRoles ansible]# cat test_ansible.yml

---
- hosts: webserver
  user: root
  tasks:
    - name: output message.
      debug: msg="{{ message }}"

    - name: output info
      debug: msg="We want {{ item.value.age }} {{ item.key }} !" 
      with_dict: "{{ Info }}"

Run ansible-playbook

[root@DevopsRoles ansible]# ansible-playbook -i inventory/hosts test_ansible.yml

The terminal output as below

Example Ansible playbook roles

Ansible structure folder and file as below

ansible/
├─inventory/
│ └─hosts
├─group_vars/
│ └─webserver.yml
├─files/
│ └─file_webserver
├─templates/
│ └─template_webserver.j2
├─roles/
│ ├─role-common/
│ │ └─tasks/
│ │  └─main.yml
│ └─role-web/
│   └─tasks/
│   └─main.yml
├─test.yml
├─main.yml
└─master.yml

Creating the folder and file for ansible-playbook roles

[root@DevopsRoles ansible]# pwd
/root/ansible
[root@DevopsRoles ansible]# touch master.yml
[root@DevopsRoles ansible]# mkdir roles
[root@DevopsRoles ansible]# mkdir roles/{role-common,role-web}
[root@DevopsRoles ansible]# mkdir roles/role-common/tasks
[root@DevopsRoles ansible]# mkdir roles/role-web/tasks
[root@DevopsRoles ansible]# touch roles/role-common/tasks/main.yml
[root@DevopsRoles ansible]# touch roles/role-web/tasks/main.yml

Package operation can be done with the Yum module etc. It is an image as below.

- name: install packages from yum
  yum: name={{ item }} state=latest
  with_items:
    - nginx

In the above code, “Nginx” is installed”, but if “state=absent” it will be a code indicating that it is not installed.

You can set up CRON job using the CRON module.

- name: register cron job
  cron: name="check ping" day="*/2" hour="12" minute="0" job="ping -c 3 192.168.1.113"

Of course, you can create directories and place files in Ansible. Directory creation is done with the file module.

- name: create directories
  file: path={{ item.path }} owner={{ item.owner }} group={{ item.group }} mode=0{{ item.mode }} state=directory
  with_items:
    - { "path":"/opt/ansible", "owner":"root", "group":"root", "mode":"755" }
    - { "path":"/opt/data", "owner":"root", "group":"root", "mode":"755" }

Copy Static file using copy module ansible

- name: copy files
  copy: src=./files/file_webserver dest=/opt/ansible/file_webserver owner=root group=root mode=0755

To copy the Dynamic file for Ansible

- name: copy template files
  template: src=./templates/template_webserver.j2 dest=/opt/ansible/template_webserver owner=root group=root mode=0755

I have written in jinja2 file format.

cat templates/template_webserver.j2

#This is a jinja template file.
{{ message }}
#jinja template can extract variables. like, ...
{% for key,value in Info.iteritems() %}
I am {{ value.age }} {{ key }} !
{% endfor %}

In the jinja template, you can also use variables in almost the same way as in Playbook.
I can also iterate with for statement like with_dict, but here you can use it without putting the item.

The final, all the contents so far.

[root@DevopsRoles ansible]# cat main.yml

The content main.yml file as below

- hosts: webserver
  user: root
  tasks:
    - name: install packages from yum
      yum: name={{ item }} state=latest
      with_items:
        - nginx

- name: register cron job
      cron: name="check ping" day="*/2" hour="12" minute="0" job="ping -c 3 192.168.1.113"

    - name: create directories
      file: path={{ item.path }} owner={{ item.owner }} group={{ item.group }} mode=0{{ item.mode }} state=directory
      with_items:
        - { "path":"/opt/ansible", "owner":"root", "group":"root", "mode":"755" }
        - { "path":"/opt/data", "owner":"root", "group":"root", "mode":"755" }

    - name: copy files
      copy: src=./files/file_webserver dest=/opt/ansible/file_webserver owner=root group=root mode=0755

    - name: copy template files
      template: src=./templates/template_webserver.j2 dest=/opt/ansible/template_webserver owner=root group=root mode=0755

Check Mode is a mode that does not actually change, you can check which part will be changed when you run Playbook. Generally, it is called Dry run mode for Ansible. If you give –check as an option, it works in Check Mode.

[root@DevopsRoles ansible]# ansible-playbook --check -i inventory/hosts main.yml

The screen output terminal:

Let’s use the -v option to see it in more detail.

[root@DevopsRoles ansible]# ansible-playbook --check -i inventory/hosts main.yml -v

Run Ansible Playbook.

[root@controller ansible]# ansible-playbook -i inventory/hosts main.yml

The screen output terminal:

Using Ansible role

The tasks are described collectively in one YAML file so far, but this does not work well when creating similar hosts.
Let’s cut out some of the tasks as roles and try to make them into parts.

[root@DevopsRoles ansible]# cat master.yml

The content master.yml file as below

- hosts: webserver
  user: root
  tasks:
    - name: register cron job
      cron: name="check ping" day="*/2" hour="12" minute="0" job="ping -c 3 192.168.1.113"

  roles:
    - role-common
    - role-web

[root@DevopsRoles ansible]# cat roles/role-common/tasks/main.yml

The content main.yml file for role-common as below

- name: install packages from yum
  yum: name={{ item }} state=latest
  with_items:
    - nginx

- name: create directories
  file: path={{ item.path }} owner={{ item.owner }} group={{ item.group }} mode=0{{ item.mode }} state=directory
  with_items:
    - { "path":"/opt/ansible", "owner":"root", "group":"root", "mode":"755" }

- name: copy files
  copy: src=./files/file_webserver dest=/opt/ansible/file_webserver owner=root group=root mode=0755

[root@DevopsRoles ansible]# cat roles/role-web/tasks/main.yml

The content main.yml for role-web as below

- name: install packages from yum
  yum: name={{ item }} state=latest
  with_items:
   - nginx

- name: create directories
  file: path={{ item.path }} owner={{ item.owner }} group={{ item.group }} mode=0{{ item.mode }} state=directory
  with_items:
    - { "path":"/opt/data", "owner":"root", "group":"root", "mode":"755" }

- name: copy template files
  template: src=./templates/template_webserver.j2 dest=/opt/ansible/template_webserver owner=root group=root mode=0755

Do not say that handling with_items is not good just because I just cut out (lol)

The role called by roles is searched under the name under the roles directory, and main.yml directly under tasks is executed.
You can use dependencies etc to have a dependency on the role, but we will not handle it this time.

Let’s do it.

[root@DevopsRoles ansible]# ansible-playbook --check -i inventory/hosts master.yml

The screen output terminal:

Run ansible-playbook

[root@DevopsRoles ansible]# ansible-playbook -i inventory/hosts master.yml

Conclusion

This tutorial provides a basic introduction to get you started with the Ansible tutorial. As you gain more experience, you can explore advanced topics like inventory management, playbook organization, and integration with other tools and systems.

Through the article, you can use Ansible tutorial beginners as above. I hope will this your helpful. For more details refer to Ansible tutorial.

Bash sleep until time

How to Bash sleep until time or delay a specific amount of time. How do I pause for 5 seconds in a bash shell script on a Linux? Bash script the essential for DevOps Roles.

To make a Bash script sleep until a specific time, you can use the sleep command in combination with the date command to calculate the remaining time until the desired time is reached.

In Linux, the sleep command to add delay for a specified amount of time.
The syntax sleep command

sleep NUMBER[SUFFIX]

Where SUFFIX:

  • s for seconds (the default)
  • m for minutes.
  • h for hours.
  • d for days.

Bash sleep until time

Examples

To sleep for 5 seconds

sleep 5

To sleep for 5 minutes

sleep 5m

How do I pause my bash shell script until time for 5 second

In DOS, To pause command execution until the user pressed a key. In Linux, Use the read command with the -p option

read -rsp

Explanation

  • -r specifies the raw mode, which doesn’t allow combined characters like “\” or “^”.
  • -s specifies the silent mode
  • -p $’prompt’ specifies the prompt
  • -n 1 specifies that it only needs a single character.
  • -t 5 specifies a timeout of 5 seconds

Bash shell pause function

#!/bin/bash
# init
function pause(){
read -sp "$*"
}

pause 'Press [Enter] key to continue...'

The screen output terminal:

Conclusion

Thought the article, you can use Bash sleep until the time as above. I hope will this your helpful. For more details refer to Bash script.

Bash script arguments into a function

How to pass arguments into a function? How to Bash all arguments into a function? Bash script the essential for DevOps Roles.
Use variable $1, $2, $3 …$n to access argument pass to the function.

Bash script arguments

  • $# Number of arguments
  • $@ All arguments, starting from first
  • $1 First argument

Example

#!/bin/bash
function Name() {
   arg1=Argument1;
   arg2=Argument2;
   arg3=Argument3;
   if [ $# -eq 3 ]; then
      arg1=$1;
      arg2=$2;
      arg3=$3;
   fi
   echo "1st argument: $arg1"
   echo "2nd argument: $arg2"
   echo "3nd argument: $arg3"
}
Name $1 $2 $3

To invoke the function use syntax:

Name huu phan www.devopsroles.com

Where

Name: Function Name
huu: Argument #1 passed into the function
phan: Argument #2 passed into the function
www.devopsroles.com: Argument #3 passed into the function

Bash all arguments into a function

#!/bin/bash
function Name() {
   args=("$@")
   echo "Number of arguments: $#"
   echo "1st argument: ${args[0]}"
   echo "2nd argument: ${args[1]}"
   echo "3nd argument: ${args[2]}"
}
Name $1 $2 $3

The screen output terminal:

Conclusion

Thought the article, you can use Bash script arguments into a function as above. I hope will this your helpful. More details refer to Bash script.

Bash script run by root or not

How do I check bash script is being run as a root user or not. when creating a new account a user ID is assigned to each user. Bash shell store value user ID is $UID and $EUID variable. Bash script the essential for DevOps Roles.

Example, To check bash script run by root or not.

Using $UID variable

#!/bin/bash
if [ "$(id -u)" != "0" ]; then
   echo "Please run by root user" 2>&1
   exit 1
else
   echo "Mounting...."
   mount /dev/sdb4 /mnt/disk4
fi

Using $EUID variable

#!/bin/bash
if [[ $EUID -ne 0 ]]; then
   echo "Please run by root user" 2>&1
   exit 1
else
   echo "Mounting...."
   mount /dev/sdb4 /mnt/disk4
fi

Conclusion

Thought the article, you can use Bash script run by root or not as above. I hope will this your helpful. More details refer to Bash script.

Debug Bash Script

Introduction

How to debug a bash script? you can investigate the causes of the problems so you can apply fixes. Yeah, I will guide you turn on debug bash script. Bash script the essential for DevOps Roles.

Bash scripting is a powerful tool for automating tasks in Linux and Unix environments. However, like any programming language, debugging errors in Bash scripts can be challenging without the right techniques.

In this guide, we’ll explore how to debug Bash scripts effectively, from basic troubleshooting methods to advanced debugging tools. Whether you’re a beginner or an experienced sysadmin, mastering these techniques will save you time and help avoid unnecessary frustrations.

Why Debugging Bash Scripts is Important

Debugging is crucial to ensure your scripts function as intended. Bash scripts often interact with files, processes, and other programs, making it essential to quickly identify and resolve errors. Debugging not only improves script reliability but also deepens your understanding of Bash’s functionality.

How to Debug Bash Scripts: Techniques and Tools

1. Use the set Command for Debugging

The set command enables or disables shell options, making it highly useful for debugging. Common options include:

  • -x: Displays each command and its arguments as they are executed.
  • -e: Exits immediately if a command returns a non-zero status.
  • -u: Treats unset variables as errors.

Example:

#!/bin/bash
set -x  # Enable debugging

# Example script
name="Debugging"
echo "Hello, $name!"
set +x  # Disable debugging

2. Use bash -x for Script Debugging

Run your script with the -x option to trace each command:

bash -x your_script.sh

This provides a detailed execution trace, helping you pinpoint where errors occur.

3. Add echo Statements for Manual Debugging

Using echo is a simple yet effective way to debug scripts. Insert echo statements at key points to check variable values and script flow.

Example:

#!/bin/bash
echo "Starting script..."
value=$((5 + 5))
echo "Value is: $value"

4. Redirect Debug Output to a File

For lengthy scripts, redirect debug output to a file for easier analysis:

bash -x your_script.sh > debug.log 2>&1

5. Use trap for Error Handling

The trap command executes a specified action when a signal is received. Use it to clean up resources or log errors.

Example:

#!/bin/bash
trap 'echo "Error occurred at line $LINENO"' ERR

# Example script
cp nonexistent_file.txt /tmp/

6. Advanced Debugging with DEBUG Hook

The DEBUG trap executes before each command, allowing for fine-grained debugging.

Example:

#!/bin/bash
trap 'echo "Executing line: $BASH_COMMAND"' DEBUG

echo "This is a test."
value=$((10 + 10))
echo "Value: $value"

Debugging Examples: From Basic to Advanced

Basic Debugging

Scenario: Missing File Error

#!/bin/bash
file="data.txt"

if [ -f "$file" ]; then
  echo "File exists."
else
  echo "File not found."
fi

Use set -x to identify why $file is not found.

Intermediate Debugging

Scenario: Incorrect Variable Assignment

#!/bin/bash
name=JohnDoe  # Missing quotes
echo "Hello, $name!"

Debug with bash -x to see how name is interpreted.

Advanced Debugging

Scenario: Loop Execution Issue

#!/bin/bash
for i in {1..5}; do
  echo "Processing item $i"
done

Run with trap and DEBUG to confirm loop logic.

Popular Debugging Tools

ShellCheck

An open-source tool that identifies errors and suggests improvements in your scripts.

sudo apt install shellcheck
shellcheck your_script.sh

strace

A tool for tracing system calls made by your script.

strace -o trace.log bash your_script.sh

grep

Useful for filtering debug logs:

grep "error" debug.log

Use set builtin command

Bash script can tun on or off using set command

  •  Display commands and their arguments: set -x
  • Display shell input lines: set -v
  • This may be used to check a shell script for syntax errors. To read commands but do not execute them: set -n
#!/bin/bash
## Turn on debug mode ##
set -x 
echo "Users currently on the machine"
w
## Turn OFF debug mode ##
set +x

The screen output terminal:

Frequently Asked Questions (FAQ)

1. What is the difference between set -x and bash -x?

  • set -x: Enables tracing within a script.
  • bash -x: Traces commands when running a script externally.

2. How do I debug a function in a Bash script?

Use set -x or echo within the function to trace its behavior:

my_function() {
  set -x
  # Function code
  set +x
}

3. How can I debug scripts in production?

Redirect debug output to a log file to avoid exposing sensitive information:

bash -x your_script.sh > /var/log/debug.log 2>&1

4. What are the best practices for debugging large scripts?

Break the script into smaller functions or modules. Debug each part individually before integrating.

External Resources

Conclusion

Debugging Bash scripts may seem daunting, but with the right tools and techniques, it becomes manageable. From leveraging set -x and trap to employing tools like ShellCheck and strace, there’s a method for every scenario. By mastering these strategies, you’ll write more robust and error-free scripts.

Debugging is not just about fixing errors-it’s a learning process that deepens your understanding of Bash. Start with the basics, experiment with advanced tools, and continuously refine your approach. I hope will this your helpful. More details refer to Bash script.

Bash create new file with content

Introduction

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
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:

Conclusion

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.

Bash script check if directory exists

Use Bash script check if the directory exists or not exists.  In this tutorial, I will check FILE/FOLDER exists or NOT exists and Check Symbolic Link. Bash script the essential for DevOps Roles.

The syntax bash script check if directory exists

if [ -d "/path/to/directory" ] 
then
    echo "Directory /path/to/directory is exists." 
fi

Or syntax Bash script check if directory not exists

if [ ! -d "/path/to/directory" ] 
then
    echo "Directory /path/to/directory is NOT exists." 
    exit 99
fi

Check if the file is exists

if [ -f "/path/to/file" ]
then
    echo "File /path/to/file is exists."
fi

Example Bash script checks if the directory exists or file exists.

#!/bin/bash
_FILE="/home/huupv/devopsroles/folder/file.txt"
_LINK_DIR="/home/huupv/devopsroles/link_folder"

# Check Directory and File is exists
if [ -f "${_FILE}" ]
then
    echo "File ${_FILE} is exists."
    _DIR=$(dirname ${_FILE})

  if [ -d "${_DIR}" ]
  then
      echo "Directory /path/to/directory is exists."
  fi
fi
# Check Symbolic link
ls -la /home/huupv/devopsroles/ | grep "\->"
# Check Symbolic link is exists
if [ -L "${_LINK_DIR}" ]
then
    echo "Directory ${_LINK_DIR} is a symlink."
fi
# Check Directory is NOT exists
if [ ! -d "/home/huupv/devopsroles/folder2" ]
then
    echo "Directory /home/huupv/devopsroles/folder2 is NOT exists."
    exit 99; # ERROR code 99
fi

The screen output terminal:

Summary check File/Folder exists or NOT exists

  • -L “FILE“: FILE/FOLDER exists and is a symbolic link
  • -d “Directory“: FILE exists and is a directory
  • -f “FILE” : FILE exists

Conclusion

Through the article, you can use the Bash script check if directory exists as above. I hope will this your helpful. For more details refer to the Bash script.

Understanding Bash script comments

Introduction

How to use bash script put Multiple Line Comment. Would you like to use a bash script comment in Linux?

When writing Bash scripts, it’s crucial to include comments to enhance code readability, provide explanations, and document important details. Comments are lines of text within a script that are ignored by the Bash interpreter when executing the code.

In this tutorial, we will explore the two types of comments available in Bash scripting and learn how to effectively use them.

Bash script comment

Single line comment

Single-line comments are the simplest form of comments in Bash scripting. They begin with the # (hash) symbol and continue until the end of the line.

# Comment line 1
# Comment line 2

HERE DOCUMENT COMMENT

A here document is a construct in Bash that allows you to pass multiple lines of input to a command or store them in a variable. It is not used as a form of comment.

<<COMMENT
  Comment 1
  Comment 2
  Comment N
COMMENT

Multiple line comment

While Bash does not have a built-in syntax for multi-line comments like some other programming languages, you can achieve a similar effect by using multiple single-line comments consecutively.

: '
This is a
multiple line
comment
'

Best Practices for Commenting

  • To make your Bash scripts more understandable and maintainable, consider the following best practices for commenting:
  • Use comments to describe the purpose and functionality of your code.
  • Add comments above sections of code to provide an overview of what the code does.
  • Include comments within complex code blocks to explain intricate logic or algorithms.
  • Document any assumptions, constraints, or prerequisites required for the script to function properly.
  • Comment your code as if someone else will be reading and maintaining it.
  • Avoid excessive commenting; focus on providing meaningful and concise explanations.
#!/bin/bash
_foo="Wellcome to Devopsroles.com"

# Single line 1
# Single line 2

<<COMMENT
  Comment 1
  Comment 2
  Comment N
  HERE DOCUMENT comment
COMMENT

: '
This is a
multi line
comment
'
echo ${_foo}

The screen output terminal:

Conclusion

In Bash scripting, comments play a vital role in enhancing code readability and maintaining script documentation.

Single-line comments starting with # and multi-line comments created by combining consecutive single-line comments are powerful tools for explaining code, providing instructions, and temporarily disabling sections.

I hope will this your helpful. For more details refer to Bash script.

Bash script read time

You can use the date command to display or set the current date and time. In this tutorial, I will write small program use Bash script read time. Bash script the essential for DevOps Roles.

The syntax of date command

date +"%FORMAT"

Show current time

[huupv@huupv devopsroles]$ date +"%T"

The screen output terminal:

Set variable _now for the current time

_now=$(date +"%T")
echo "Current time : ${_now}"

The screen output terminal:

Create bash script bash_read_time.sh file

#!/bin/bash
# Display text at given row and column
function show(){
  local x=$1
  local y=$2
  local txt="$3"
  tput cup $x $y
  echo "$txt"
}
while true
do
  clear
  # Get the system time 12 hour clock time
  now="$(date +"%r")"
  # Show main
  show 11 11 "MAIN MENU for $HOSTNAME - $now"
  show 11 11 "1. System info "
  show 12 11 "2. OS version "
  show 13 11 "3. Exit "
  tput cup 16 11; read -t 2 -p "Choice [1-3] ? " _select
  # do something
  case ${_select} in
    1) read -t 2 -p "Showing system info, wait..." ;;
    2) read -t 2 -p "Showing apache info, wait..." ;;
    3) echo "Bye."; exit 0;;
  esac
done

Run bash script read time

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

Conclusion

Thought the article, you can use Bash script read time. I hope will this your helpful. More details refer to Bash script.

Devops Tutorial

Exit mobile version