Common Linux questions asked in Devops

Amay JaiswalAmay Jaiswal
19 min read

Question1: Explain the Boot process in Linux?

The boot process is the sequence of steps that start a Linux machine. We will explore what happens behind the scenes when you press the power button on a machine.

First, you power on the computer or machine. Then, the BIOS or UEFI starts up. These are pieces of software that prepare all the main parts of your computer, like the keyboard, screen, hardware, and drivers, for use. UEFI is the newer option, offering faster boot times and better security features, like secure boot, compared to the traditional BIOS.

Difference between BIOS and UEFI:

One key difference is approach to the storage.

Next step is UEFI/BIOS runs a check called power-on self test or POS, this test makes sure all the hardware components are working fine, If POST finds a problem it will often show a error message on the screen. If everything is working fine with POST, BIOS/UEFI needs to find and load up the boot loader software. The boot loader is set to check the hardrive first then USB drivers or CD’s you can customize the order is BIOS settings.

On a BIOS system boot loader stays in the first little chunk of hardrive called “Master Boot Record”

For UEFI, there’s a seperate parition that store files like .efi boot loader file.

Key Jobs for boot loader are:

  1. Locate the operating system system kernel on the disk.

  2. Load the kernel on the computer memory.

  3. Start runnig the kernel code.

Some common boot loaders are GRUB2 and LILO (Linux Loader), though LILO is outdated and rarely used. GRUB2 is the most widely used today; it can handle booting multiple operating systems and offers a nice interface with graphical or text-based menus.

Once GRUB2 loads, it inserts the Linux kernel into memory and hands control over to the kernel to complete the startup process. The kernel takes over and begins initiating all the background processes and services.

First, it decompresses itself into memory, checks the hardware, and loads the device drivers and other kernel modules.

Next, an initial module called the init module starts, which in modern Linux is called Systemd. It has many responsibilities to get the system booted and ready to use. It checks any remaining hardware that needs drivers loaded, mounts all different file systems and disks, and starts launching all the background services you need, like networking, sound, and power management. It handles user login once you reach the graphical prompt and also loads your desktop environment with panels and menus.

Systemd uses target configuration files to decide which mode you should boot into, like the multi-user text-only target or the graphical target.

Question2: How can you create zero size file in linux?

The Linux touch command is used to create a file without any content. The file created using the touch command is empty with zero bytes. This command can be used when the user doesn't have data to store at the time of file creation.

Echo command can also be used to create a file with zero bytes if there is no data to be stored on the file, linux command printf prints a formatted string to the standard output with no data appending on the file.

Question3: What is the first line typically written in a shell script? What is its meaning? What happens if this line is omitted, and how do you run the script in such a case?

The first line typically written in a shell script is called the "shebang," and it usually looks like this:

#!/bin/bash

Meaning:

  • The #! (shebang) tells the operating system which interpreter to use to execute the script. In this case, /bin/bash specifies that the script should be run using the Bash shell.

If Omitted:

If the shebang line is omitted, the script may still run, but it will be executed using the current shell from which you run it. This could lead to issues if the script uses syntax or features specific to a different shell.

Running the Script:

If the shebang is omitted, you can run the script by explicitly invoking the desired interpreter. For example, if you want to run a script named script.sh that is intended for Bash, you would do:

bash script.sh

This way, the script will run in the correct environment, regardless of the current shell.

Question 4: How can you run a shell script in the background in Linux?

To run a shell script in the background in Linux, you can use the & symbol at the end of the command. Here’s how to do it:

  1. Using &:

      ./script.sh &
    

    This will execute script.sh in the background, allowing you to continue using the terminal.

  2. Using nohup: If you want the script to continue running even after you close the terminal, you can use nohup:

       nohup ./script.sh &
    

    This will redirect the output to a file named nohup.out by default, unless you specify a different output file.

  3. Using disown: If you’ve already started the script in the foreground, you can suspend it with Ctrl + Z, then run:

      bg disown
    

    This sends the job to the background and removes it from the shell’s job table, allowing it to continue running after the terminal is closed.

  4. Checking Background Jobs: You can check the status of your background jobs with:

jobs

Stopping a Background Job:

To stop a background job, you can use the kill command with the job’s process ID (PID)

This should help you run and manage shell scripts in the background effectively

kill <PID>

Question 5: what is a crontab in Linux? Explain how it works and how to configure and schedule a job using crontab.

What is cron?
Cron is a utility in Linux systems for scheduling tasks. The Cron daemon runs in the background to enable this feature. It reads the crontab (cron tables) to execute predefined scripts.

With a specific syntax, you can set up a cron job to automatically run scripts or other commands. For individual users, the cron service checks the following file: /var/spool/cron/crontabs

What are cron jobs in Linux?

Any task that you schedule through crons is called a cron job. Cron jobs help us automate our routine tasks, whether they're hourly, daily, monthly, or yearly.

Format of cron jobs: Each line in a crontab file represents a scheduled task, defined by the time and date fields followed by the command to be executed.

Time Fields: The time format consists of five fields:

How to Control Access to crons?

In order to use cron jobs, an admin needs to allow cron jobs to be added for users in the '/etc/cron.allow' file. First, to use cron jobs, you need to check if the cron service is running. If it's not installed, you can download it using the package manager. Use this command to check:

# Check cron service on Linux system
sudo systemctl status cron.service

Crontab Syntax:

The basic syntax of a crontab entry is:

* * * * * command_to_execute

Examples of Time Fields

  • * * * * *: Every minute

  • 0 * * * *: At the start of every hour

  • 0 12 * * *: At noon every day

  • 0 1 * * 0: At 1 AM every Sunday

How to Configure and Schedule a Job Using Crontab:

  • Open Crontab: To edit your user’s crontab file, use the command:

  •   crontab -e
    
  • Add a Cron Job: In the editor that opens, you can add a line following the format described above. For example, to run a script located at /path/to/script.sh every day at 2 AM, you would add:

        0 2 * * * /path/to/script.sh
    
  • Save and Exit: After adding your entries, save the file and exit the editor. The changes will be automatically applied.

  • List Current Cron Jobs: To see the current cron jobs for your user, run:

        crontab -l
    
  • Remove Crontab: If you need to delete all your cron jobs, you can use:

        crontab -r
    

    Below is the summary of the cron job syntax.

        *   *   *   *   *  sh /path/to/script/script.sh
        |   |   |   |   |              |
        |   |   |   |   |      Command or Script to Execute        
        |   |   |   |   |
        |   |   |   |   |
        |   |   |   |   |
        |   |   |   | Day of the Week(0-6)
        |   |   |   |
        |   |   | Month of the Year(1-12)
        |   |   |
        |   | Day of the Month(1-31)  
        |   |
        | Hour(0-23)  
        |
        Min(0-59)
    

    Important Considerations

    • Environment Variables: Cron jobs run in a limited environment, so it’s often a good idea to define any necessary environment variables at the beginning of the crontab or specify the full path to commands.

    • Logging: To capture output and errors from cron jobs, you can redirect output to a file. For example:

          0 2 * * * /path/to/script.sh >> /path/to/logfile.log 2>&1
      
    • Permissions: Ensure that the scripts or commands you’re trying to run have the appropriate permissions set.

Question 6: How do you allow ports in Linux?
Allowing ports in Linux typically involves configuring the firewall to permit traffic through specific ports. The method you use depends on which firewall system is in place. The most common ones are iptables, firewalld, and UFW (Uncomplicated Firewall). Here’s how to allow ports using each of these tools:

Using iptables

  1. Allow a Port: To allow a specific port (e.g., TCP port 8080), run:

      sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT
    
  2. Save the Rules: To ensure the rules persist after a reboot, you need to save them:

      sudo iptables-save | sudo tee /etc/iptables/rules.v4
    
  3. View Current Rules: To see the current iptables rules:

      iptables -L
    

Using firewalld

  1. Start firewalld: Ensure that firewalld is running:

      sudo systemctl start firewalld
      sudo systemctl enable firewalld
    
  2. Allow a Port: To allow a specific port (e.g., TCP port 8080):

      sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
    
  3. Reload the Firewall: Apply the changes:

      sudo firewall-cmd --reload
    
  4. List Allowed Ports: To check which ports are allowed:

      sudo firewall-cmd --list-all
    

Using UFW

  1. Enable UFW: If UFW is not enabled, you can enable it with:

      sudo ufw enable
    
  2. Allow a Port: To allow a specific port (e.g., TCP port 8080):

      sudo ufw allow 8080/tcp
    
  3. Check Status: To see the current status and rules:

      sudo ufw status
    
  4. Disable UFW: If you need to disable it temporarily:

      sudo ufw disable
    

Summary

  • iptables: Use iptables commands to add rules and save them.

  • firewalld: Use firewall-cmd to manage rules, applying changes with a reload.

  • UFW: Simplified command-line tool to easily allow or deny ports.

Question 7: How do you troubleshoot a remote server that is experiencing issues?

1. Initial Checks

  • Ping the Server: Check if the server is reachable.

        ping <server-ip>
    
  • Check DNS Resolution: Ensure the domain name resolves correctly.

        nslookup <domain>
    

2. Access Logs

  • SSH Access: Attempt to SSH into the server.

        ssh user@<server-ip>
    

    If SSH fails, check your connection, any power outage, credentials, or if the SSH service is running.

  • Review Logs: Once logged in, check system logs for errors.

    • Syslog: /var/log/syslog

    • Auth Log: /var/log/auth.log (for SSH issues)

    • Application Logs: Check logs for specific applications that are having issues.

3. Resource Utilization

  • Check CPU and Memory Usage:

        top
    

    or

        htop
    
  • Disk Space: Ensure there’s enough disk space.

        df -h
    
  • I/O Wait: Check for high disk I/O which might indicate a bottleneck.

        iostat
    

4. Network Configuration

  • Check Network Interfaces: Ensure network interfaces are up.

        ip a
    
  • Routing Table: Check routing to see if it’s configured correctly.

        ip route
    
  • Firewall Rules: Verify that firewall rules aren’t blocking necessary traffic.

        sudo iptables -L
    

    or

        sudo firewall-cmd --list-all  # for firewalld
    

5. Service Status

  • Check Running Services: Ensure critical services are running.

        systemctl status <service-name>
    
  • Restart Services: If a service is down or unresponsive, try restarting it.

        sudo systemctl restart <service-name>
    

6. Application-Specific Troubleshooting

  • Check Configuration Files: Ensure application configurations are correct.

  • Review Application Logs: Look for errors or warnings specific to the application.

7. Performing Tests

  • Test Connectivity: Use tools like telnet or nc to check connectivity on specific ports.

        telnet <server-ip> <port>
    
  • Run Diagnostics: For web servers, tools like curl or wget can help verify responses.

        curl -I http://<server-ip>
    

8. Consult Documentation and Community

  • If you’re still facing issues, consult the documentation for the specific application or service.

  • Search online forums or communities for similar issues.

9. Gathering More Information

  • Strace: Use strace to trace system calls for a running process if needed.

        strace -p <pid>
    
  • Debugging Tools: Use tools like tcpdump or wireshark for deeper network analysis.

10. Plan for Recovery

  • If issues persist and affect production, consider rolling back to a previous state, restoring from backups, or implementing failover measures.

Summary

Start with basic connectivity checks, review logs, monitor resources, check services, and conduct application-specific troubleshooting. Document your steps for future reference, and don’t hesitate to seek help from documentation or communities if needed.

Question 8: What are the 𝗽𝗶𝗻𝗴, 𝘁𝗲𝗹𝗻𝗲𝘁, 𝗰𝘂𝗿𝗹, and 𝘄𝗴𝗲𝘁 commands in Linux?

  1. Ping:

Question 11:

  • Purpose: Tests the reachability of a host on a network.

  • Usage: Sends ICMP Echo Request packets to the specified host and waits for a reply.

  • Example:

        ping google.com
    
    1. telnet
  • Purpose: Establishes a text-based communication session with a remote server, typically over TCP.

  • Usage: Can be used for testing connectivity to a specific port or to log into remote systems.

  • Example:

        telnet example.com 80
    

3. curl

  • Purpose: Transfers data to or from a server using various protocols (HTTP, HTTPS, FTP, etc.).

  • Usage: Often used to fetch web pages or send data via POST requests.

  • Example:

        curl http://example.com
    

4. wget

  • Purpose: Downloads files from the web.

  • Usage: Supports downloading via HTTP, HTTPS, and FTP. It's non-interactive, meaning it can run in the background.

  • Example:

        wget http://example.com/file.zip
    

Each command serves its own purpose, with ping mainly for testing connectivity, telnet for interactive sessions, and curl and wget for data transfer and file downloads.

Question 9: How can you check the status of services in a Linux machine?

  • To check the status of a service in linux system there are many commands, Systemd (common in modern distributions like Ubuntu, CentOS, Debian, etc.)

  • Check the status of a specific service:

        systemctl status service_name
    
  • List all services and their statuses:

        systemctl list-units --type=service
    

    2. SysVinit (older distributions)

  • Check the status of a specific service:

        service service_name status
    
  • List all the services

        service --status-all
    

    3. Using ps command

    • To see if a service's process is running, you can use:

          ps aux | grep service_name
      

4. Using netstat or ss

  • To check if a service is listening on a specific port:

        netstat -tuln | grep port_number
    

or

    ss -tuln | grep port_number

5. Using pgrep

  • To find the process ID (PID) of a running service:

        pgrep service_name
    

Question 10: How do you kill a process in Linux?

  • To kill a process in linux you can use “kill” command.

  • Find the Process ID (PID): You can find the PID of the process using:

        eps aux | grep process_name
    

    Kill the Process: Once you have the PID, use:

       codekill PID
    

    Force Kill (if the process doesn’t terminate):

        codekill -9 PID
    

    2. Using pkill Command

    • You can kill a process by its name directly:

          pkill process_name
      
    • Force Kill:

          pkill -9 process_name
      

      3. Using killall Command: Be careful when using this command.

      • This command kills all processes with the specified name:

            killall process_name
        
      • Force Kill:

            killall -9 process_name
        

        4. Using top or htop

        • You can run top or htop (if installed) to interactively manage processes.

        • In top, press k, enter the PID, and specify the signal (default is 15 for graceful termination).

        • In htop, you can navigate to the process and press F9 to kill it.

Notes

  • Use kill -9 or its equivalents with caution, as it forces termination without cleanup.

  • Always try to terminate processes gracefully first before using the force kill option.

    Question11: What are the 𝗻𝗶𝗰𝗲 and 𝗿𝗲𝗻𝗶𝗰𝗲 commands in Linux?

    The Linux nice and renice commands are used to change process priorities. They let you set a custom nice value for a process when it starts or adjust the nice value of a running process.

    1. nice

    • Purpose: Starts a new process with a specified scheduling priority. It allows you to influence how the operating system allocates CPU time to the process.

    • Usage: The nice command can be used to launch a program with a higher or lower priority. The priority value ranges from -20 (highest priority) to 19 (lowest priority). The default value is 0.

    • Example:

          nice -n 10 command_name
      

      This command runs command_name with a niceness value of 10, making it less favorable for CPU allocation compared to processes with a lower niceness value.

2. renice

  • Purpose: Changes the niceness value of an already running process.

  • Usage: You can use renice to adjust the priority of one or more existing processes based on their PID (Process ID).

  • Example:

        renice 5 -p PID
    

    This command changes the niceness value of the process with the specified PID to 5, making it less favorable for CPU allocation.

Important Notes

  • Only the root user can decrease the niceness value (increase the priority) of a process.

  • Regular users can only increase the niceness value (decrease the priority).

  • Adjusting the niceness values can help in managing system resources, especially on heavily loaded systems.

Question12: What is an 𝗶𝗻𝗼𝗱𝗲 in Linux?

  • In Linux, an inode (index node) is a data structure on a filesystem that stores information about a file or a directory, except for its name and actual data. Each inode contains metadata about the file, such as:

    • File type (regular file, directory, symlink, etc.)

    • Permissions (read, write, execute)

    • Ownership (user ID and group ID)

    • Timestamps (creation, modification, and last access times)

    • Size of the file

    • Pointers to the data blocks where the file's actual content is stored

When you create a file, the filesystem allocates an inode for it, which is then used to track the file's attributes. Inodes allow the filesystem to efficiently manage and access files. Each file system has a limited number of inodes, which can impact the ability to create new files even if there is free disk space available.

  • File-level inode

    We can also look at the inode number of a specific file. To do this, we use the ls -i command on the desired file. For example:

  • Directory-level inode

    Just like with files, we can also see the inode of a directory. To do this, we use the ls -i command again with a few additional options. For example:

Question 13: How do you check CPU utilization in Linux?

You can check the CPU utilization in Linux using several commands. Here are a few common ones:

  1. top: This command provides a dynamic, real-time view of system processes, including CPU usage.

      top
    
  2. htop: An enhanced version of top, it provides a more user-friendly interface with additional features. You may need to install it first.

      htop
    
  3. mpstat: Part of the sysstat package, it shows CPU usage for each available processor.

      mpstat -P ALL 1
    

    (This will update every second.)

  4. vmstat: This command provides a summary of various system statistics, including CPU utilization.

      vmstat 1
    
  5. sar: Also part of the sysstat package, it can collect and report various system activities.

      sar 1
    
  6. iostat: This command reports on CPU utilization along with input/output statistics for devices.

      iostat -c 1
    
  7. /proc/stat: You can also view CPU statistics directly from the proc filesystem.

     proc/stat
    

Each of these commands provides different levels of detail and features, so you can choose one based on your specific needs.

Question 14: What are the differences between the 𝘁𝗼𝗽 and 𝗵𝘁𝗼𝗽 commands?

The top and htop commands in Linux are both used for monitoring system processes and resource usage, but they differ in several ways:

  1. The top command is older and comes preinstalled on all Linux distributions, htop is newer and adds color, providing a more interactive user interface with graphical elements (like bars) for CPU, memory, and swap usage, making it easier to interpret.

    This is how the top command looks like in the default settings:
    Nothing fancy shows relevant info in bold.

    htop here you have various advantages over the top utility as it shows the following details by default:

    • How every core of your processor is utilized with individual progress bars.

    • Beautiful colored output.

    • Ability to use the mouse pointer to select options with the ability to scroll through the processes.

2. Interactivity:

  • top: Provides limited interactivity. You can use certain keyboard shortcuts, but the controls are less intuitive.

  • htop: Highly interactive and user-friendly. You can navigate processes easily using arrow keys and perform actions like killing processes with simple commands.

    3. Availability:

  • You will find the presence of top and htop in the default repository of almost every repository.

    But the top comes pre-installed with every modern UNIX-like system whereas the htop does not come pre-installed in the majority of systems.

    4. Process Management:

    • top: Allows you to kill processes using keyboard shortcuts, but it can be cumbersome.

    • htop: Provides a straightforward way to manage processes, including an easy way to kill or renice processes directly from the interface.

5. Resource Visualization:

  • top: Displays resource usage as simple numbers without visual aids.

  • htop: Uses visual indicators, such as colored bars for CPU and memory, making it easier to quickly assess system health.

Question 15: What is a 𝗺𝗼𝘂𝗻𝘁 in Linux, and how do you create one? A mount in Linux is a file system that's attached to a specific directory in the file system hierarchy. This allows the user and system to access the files and directories of the mounted device.

How to Create a Mount in Linux

Here are the steps to create a mount:

  1. Identify the Filesystem: First, determine the device you want to mount (e.g., a hard drive, USB stick). You can use the lsblk or fdisk -l command to list available devices.

      lsblk
    
  2. Create a Mount Point: This is a directory where the filesystem will be attached. You can create it using the mkdir command.

      sudo mkdir /mnt/my_mount_point
    
  3. Mount the Filesystem: Use the mount command to attach the filesystem to the mount point. Replace /dev/sdXn with your actual device identifier.

      sudo mount /dev/sdXn /mnt/my_mount_point
    
  4. Verify the Mount: You can check if the filesystem is mounted using the df or mount command.

      df -h
      # or
      mount | grep /mnt/my_mount_point
    

Optional: Automate Mounting on Boot

To automatically mount a filesystem on boot, you can add an entry to the /etc/fstab file. The format typically looks like this:

        /dev/sdXn   /mnt/my_mount_point   ext4   defaults   0   2

Replace the filesystem type (ext4 in this example) with the appropriate type for your filesystem (e.g., ntfs, vfat).

Unmounting

When you're done with the filesystem, you can unmount it using:

        sudo umount /mnt/my_mount_point

By following these steps, you can successfully create a mount in Linux and manage access to different filesystems.

0
Subscribe to my newsletter

Read articles from Amay Jaiswal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Amay Jaiswal
Amay Jaiswal

AWS Cloud & DevOps Engineer | Cloud Computing | Linux | Terraform & CloudFormation | AWS (EC2, S3, Lambda, API Gateway, DynamoDB, IAM) | Docker | Jenkins | CI/CD Pipelines | MySQL | Java | Jira | Postman | Git/GitHub