Sign In
Sign In

Writing Scripts in Linux Bash

Writing Scripts in Linux Bash
Hostman Team
Technical writer
Linux
14.10.2024
Reading time: 12 min

Bash (Bourne-Again SHell) is a command interpreter in UNIX-like operating systems that allows for task automation at the command line level. Bash scripts are files containing a sequence of commands that can be executed by the Bash interpreter.

Bash scripts can be used to automate repetitive tasks. For example, if you need to generate and send a report via email every day, you can write a bash script that performs these actions automatically. This saves a lot of time and reduces the likelihood of errors.

In this article, we will cover the basic concepts and tools for writing Bash scripts in Linux.

Bash Script Syntax

Bash scripts can be written in any text editor and must have executable permissions. Let’s consider some of the most popular editors:

  • Nano is a simple text editor that comes with most Linux distributions. It has an intuitive interface and useful features like syntax highlighting.

  • Vim is one of the most popular text editors for Linux, though it may seem complicated for beginners. Vim offers many features to speed up coding, such as syntax highlighting, autocompletion, and macros.

  • Emacs is another popular text editor for Linux. It also has many features that can simplify the coding process. One of its main features is the ability to run the Bash interpreter inside the editor, allowing you to test scripts without exiting the editor.

At the beginning of each script, there must be a line called a shebang, which tells the operating system which interpreter to use to execute the script. The shebang should start with a hash symbol (#) followed by an exclamation mark (!), and then the path to the interpreter. To use the Bash interpreter, the shebang will look like this:

#!/bin/bash

While writing the script, you can also leave comments that start with a hash symbol and continue until the end of the line. Comments will not be executed by the interpreter and are used to describe the functionality of the script. For example:

# This is a comment

Below, we will write our first script. Suppose we want to create a script in Linux that greets the user and displays the current date and time on the screen. To do this, create a file named greeting.sh in any directory on your computer and add the following code:

#!/bin/bash
echo "Hello, $USER!"
echo "Today is $(date)"

The first line indicates that this is a Bash script. The next line, echo "Hello $USER!", outputs a greeting with the current user's name. $USER is a system variable that contains the name of the current user. The third line, echo "Today is $(date)", displays the current date and time. $(date) is used to call the date command, which returns the current date and time in the system's format.

When creating a Bash script, it’s important to ensure the file is executable. To do this, you need to change the file permissions. We’ll cover this and how to run the script in the next chapter.

Running Scripts

To run a script in Linux, it must have executable permissions. To make a file executable, you can use the chmod command (short for "change mode"). This command allows you to change the access permissions of files and directories in Linux.

The syntax for the chmod command is as follows:

chmod [options] access_rights file

where access_rights is a special code that sets the access permissions for a file or directory, and file is the path to the file or directory whose permissions you want to change.

To make a file executable, you need to add the execute (x) permission to its access rights. For example, to make the greeting.sh file executable, use the following command:

chmod +x greeting.sh

This command will add execute permissions for the current user. Now, we can run the Bash script in Linux by invoking it from the terminal:

./greeting.sh

The result of running the script is shown below.

Image9

Command Line Parameters

Command line parameters allow you to pass arguments to Linux scripts when they are run. Command line parameters can be accessed in the script as $1, $2, $3, etc., where $1 is the first parameter, $2 is the second parameter, and so on.

Let's rewrite the script from the previous chapter to greet the user using a command-line argument:

#!/bin/bash
echo "Hello $1!"

Then run the script, passing the $USER argument:

./greeting.sh $USER

The result is shown below.

Image5

Additionally, you can use special command line parameters:

  • $0 — the name of the script (i.e., the name of the file that was run)

  • $# — the number of passed parameters

  • $* or $@ — a list of all passed parameters (as a single string or array, respectively)

  • $? — the return code of the last executed command

For example, to display the number of passed parameters, you can use the following code:

#!/bin/bash
echo "Hello $1!" 
echo "Number of passed parameters: $#"

The result of running the script is shown below.

Image4

Variables

Variables in Bash are used to store data, such as strings and numbers. They can be explicitly defined by assigning a value or implicitly defined through automatic assignment during certain operations. To create a variable in Bash, you need to assign it a value using an equal sign (=). For example:

company="Hostman"

Note that there should be no spaces between the variable name, the equal sign, and the value.

You can retrieve the value of a variable by specifying its name after the echo command and the $ sign. For example:

echo $company

It's also possible to assign a variable value through user input using the read command. For example, the following script prompts the user for their name and stores it in a variable:

#!/bin/bash
echo "What is your name?"
read name
echo "Hello, $name!"

The result of this script is shown below.

Image8

In Bash, there are several special variables that are automatically defined and filled by the system. For example, the $HOME variable contains the path to the user's home directory, while $PWD contains the path to the current working directory. 

Additionally, there are environment variables that are defined by the system and can be used in scripts. For example, $PATH contains a list of directories where Bash looks for executable files.

Variables can also be used to pass values between different commands and scripts. For example, to pass a variable’s value from one script to another, use the export command:

export variable_name

Conditional Operators

Conditional operators allow you to execute a specific set of actions depending on whether a condition is true or false. In Bash scripts, conditions are written in brackets and passed to the if command.

The syntax of the if operator looks like this:

if [ condition ]
then
  commands to execute if the condition is true
fi

Here, in the square brackets, you specify the condition that needs to be checked. If the condition is true, the commands between then and fi will be executed.

For example, let’s write a Linux script, evenodd.sh, that checks whether the number entered by the user is even or odd:

#!/bin/bash
echo "Enter a number: "
read n
if (( $n % 2 == 0 ))
then
  echo "The number $n is even"
else
  echo "The number $n is odd"
fi

In this example, we use the % operator, which calculates the remainder of division by 2. If the remainder is 0, the number is even; otherwise, it’s odd. The result of running the script is shown below.

Image3

Additionally, there are several comparison operators that can be used in conditional constructions:

  • -eq – equal to;

  • -ne – not equal to;

  • -gt – greater than;

  • -lt – less than;

  • -ge – greater than or equal to;

  • -le – less than or equal to.

For example, to check if the variable $a is greater than the variable $b, you can write the following:

if [ $a -gt $b ]
then
  echo "$a is greater than $b"
fi

It is important to remember that you need to use spaces around the comparison operators in conditional constructions. If there are no spaces, Bash will treat this as one large string instead of a comparison operation.

In addition to if, Bash scripts also use the case structure. This allows you to check a variable's value against several possible options. We will discuss this in the next chapter.

The Case Construction

The case construction in Bash scripts allows you to simplify writing conditional operators for comparing variables with multiple possible values.

The syntax of the case construction is as follows:

case variable in
    pattern1)
        command1
        ;;
    pattern2)
        command2
        ;;
    pattern3)
        command3
        ;;
    *)
        default command
        ;;
esac

where variable is the variable to check, pattern1, pattern2, pattern3 are the possible values to check, and command1, command2, command3 are the commands to execute depending on the value of the variable.

The * symbol at the end of the list of values is used as a default handler if none of the values match the variable.

For example, let’s look at a script that checks the day of the week and performs the corresponding action:

#!/bin/bash

day=$(date +%u)

case $day in
    1)
        echo "Today is Monday"
        ;;
    2)
        echo "Today is Tuesday"
        ;;
    3)
        echo "Today is Wednesday"
        ;;
    4)
        echo "Today is Thursday"
        ;;
    5)
        echo "Today is Friday"
        ;;
    6)
        echo "Today is Saturday"
        ;;
    7)
        echo "Today is Sunday"
        ;;
    *)
        echo "Invalid day of the week"
        ;;
esac

In this example, we use the day variable, which we define using the date +%u command. In this case, %u is used to obtain the numeric value of the day of the week, from 1 (Monday) to 7 (Sunday). Then we compare this variable with the days of the week using the case construction. If its value matches a certain day of the week, we display the corresponding message. If the value does not match any of the listed days, we display an error message.

The result of running the script is shown below. 

Image1

Loops

Loops in Bash are used to perform repetitive actions. There are two types of loops: for and while.

The for loop is used to execute commands for each element in a list.

The syntax of the for loop is as follows:

for variable in list
do
  commands
done

Here, the variable takes the value of an element from the list, and for each of them, the commands between do and done are executed.

Example:

#!/bin/bash

for i in {1..10}; do
    echo "Number: $i"
done

In this example, i takes values from 1 to 10, and for each of them, the echo "Number: $i" command will be executed. The result of running this loop will look like this:

Image10

The while loop is used to execute commands as long as the condition remains true. The syntax of the while loop is as follows:

while [ condition ]
do
  commands
done

Here, in square brackets, you specify the condition that is checked before each iteration of the loop. The commands between do and done will be executed as long as the condition is true.

Example:

#!/bin/bash

count=1
while [ $count -le 10 ]; do
    echo "Count: $count"
    count=$((count+1))
done

In this example, count increases by 1 after each iteration of the loop. When the value of count reaches 10, the loop terminates. The result of running this loop will look like this:

Image2

Functions

Functions in Bash are used to group commands into logically related blocks. Functions can be called from a script using their name. 

The syntax of a function is as follows:

function_name () {
    commands_and_expressions
}

The function name must start with a letter or an underscore and can contain only letters, numbers, and underscores. After the function name comes a list of arguments in parentheses. The commands and expressions to be executed when the function is called must be enclosed in curly braces.

Here’s an example of a function that outputs the current time and date:

#!/bin/bash

print_date () {
    echo "Today's date: $(date)"
}

print_date # Function call

The result of running the script is shown below.

Image7

Functions can also accept arguments, which are passed as parameters inside the parentheses when calling the function. Here’s an example of a function that takes two arguments and outputs their sum:

#!/bin/bash

sum_numbers () {
    result=$(( $1 + $2 ))
    echo "The sum of $1 and $2 is $result"
}

sum_numbers 10 20 # Function call

In this example, $1 and $2 are variables that contain the values of the first and second arguments, respectively. sum_numbers 10 20 will call the sum_numbers function with the arguments 10 and 20, and output the following result:

Image11

Functions can also return values using the return keyword. Let’s rewrite the previous example using this new knowledge:

#!/bin/bash

sum_numbers () {
    result=$(( $1 + $2 ))
    return $result
}

sum_numbers 12 24 # Function call
echo "The sum of the numbers is $?" # Output

Here, the result is stored in the result variable and returned from the function using the return command.

The $? variable contains the return code of the function, which in this case is the result of the sum calculation.

The result of running the script is shown below.

Image12

There is another way to handle the result of a function call without using return. Let’s slightly modify the previous script:

#!/bin/bash

sum_numbers () {
    result=$(( $1 + $2 ))
    echo $result
}
sum=$(sum_numbers 9 11)
echo "The sum of the numbers is $sum" # Output

Here, instead of using $? and return, we store the result of the function call in the sum variable and then output its value. The result is shown below.

Image6

Working with Files and Directories

Bash scripts can be used to perform various operations with files and directories in Linux. For example, to check if a file exists, you can use the following command: 

test -e filename 

If the file exists, the command will return a value of 0; otherwise, it will return a non-zero value.

To work with directories in Bash scripts, you can use commands like cd, mkdir, rmdir, ls, and others.

Script Debugging

Debugging Bash scripts can be a challenging task because problems can be caused by various factors, such as syntax errors, incorrect use of variables or functions, etc. For debugging Bash scripts, you can use tools like set -x, set -v, and set -e.

  • The set -x command allows you to display the commands before they are executed

  • The set -v command displays the values of variables before they are used

  • The set -e command stops the execution of the script in case of an error

Conclusion

Bash scripts are a powerful tool for automating tasks in UNIX-like operating systems. In this article, we covered the basic concepts and tools for writing Bash scripts, such as syntax, variables, conditional operators, loops, functions, and running scripts. We hope this guide helps you become a more productive and experienced Linux user.

You can buy Linux VPS for your projects on Hostman. 

Linux
14.10.2024
Reading time: 12 min

Similar

Linux

How to Use if-else in Bash

Many programming languages have conditional statements, such as if-else. These statements are also present in Bash, the default shell used in almost all modern Linux distributions. The if-else statements are used to check conditions — they allow the execution of specific commands depending on whether the condition is true or false. The if-else statements work exactly the same way as in any programming language. In this article, we will discuss how to use if-else statements in the Bash shell through practical examples. The if Statement in Bash The if statement in Bash allows you to execute specific commands depending on the truth value of the given condition. Two logical statements are used to check for truth: True and False. The if statement is used when you need to check a condition. It controls the flow of script execution, allowing decisions to be made based on variable values, command results, and other conditions. The if statement works as follows: First, the program checks the condition (the condition can be a command or a mathematical expression) contained in the if statement. If the condition is true, the program executes the commands listed after the then keyword. If the condition is false, the program executes the commands listed after the else statement. The syntax of the if statement in Bash is as follows: if [condition]; then # commands to execute if the condition is true fi Let's break down the operation of the if statement with a simple practical example. We will create a script that asks the user for a number, and if the number entered is greater than 10, the system will return the message "The number is greater than 10." Create a new file with a .sh extension, for example, using the nano editor: nano greater_than_10.sh Insert the following code: #!/bin/bash read -p "Enter a number: " number if [ $number -gt 10 ]; then echo "The number is greater than 10." fi Provide the file with execute permissions: chmod +x greater_than_10.sh Now, run the script: ./greater_than_10.sh Output: Enter a number: Enter any number, for example, 32, and press Enter. Since 32 is greater than 10, and this condition returns True, the program will execute the echo command. Enter a number: 32The number is greater than 10 Let’s break down the script in more detail: The conditions are written in square brackets. In this example, the -gt operator is used (greater than, equivalent to the > symbol). Next, we check the condition. If it’s True, the program executes the command after the then keyword. The script ends with the fi keyword, signaling the end of the if block. However, this script has one major drawback: it does not handle the case when the entered number is less than 10. The script will not return anything because there is no condition for that case. To address this issue, we will use the else statement, which we will discuss in the next chapter. The if-else Statement in Bash In the previous section, we ran a script with only one condition in the if statement — True. We didn’t specify any action for the False condition. As a result, if we entered a value leading to False, there was no response. If we want the script to perform specific actions for the false condition False, we need to use the else statement, which follows the if statement. The if-else statement in Bash is used to perform conditional operations. It allows the execution of specific commands depending on whether the condition is true or false. The syntax for if-else is as follows: if [condition]; then # commands executed if the condition is true else # commands executed if the condition is false fi Remember that keywords, including if and else, in Bash shell scripts are case-sensitive. Be careful when using keywords in script files. Let's consider using the if-else statements in a practical example. In this case, we will create a Bash script that asks the user for a number, and the system will display whether the number is greater than or less than 10. Create a new file with a .sh extension: nano check.sh Insert the following code: #!/bin/bash read -p "Enter a number: " number if [ $number -gt 10 ]; then echo "The number is greater than 10." else echo "The number is less than or equal to 10." fi Grant the file execute permissions: chmod +x check.sh Now, run the script: ./check.sh The algorithm for the script works as follows: After the if keyword, we specify the condition in square brackets. In this example, we use the -gt operator (greater than, equivalent to the > symbol). The condition is checked. If the condition is true, the program executes the command after the then keyword— in this case, it prints the message "The number is greater than 10". If the condition is false, the program executes the command after the else keyword, printing the message "The number is less than or equal to 10". Once one of the conditions is met, the program will end, as indicated by the fi keyword at the end. Output if the number is greater than 10: Enter a number: 56The number is greater than 10. Output if the number is less than 10: Enter a number: 6The number is less than or equal to 10. Practical Use of if-else in Bash Let's look at the practical application of the if-else statement in Bash, which can be used when writing scripts. Script Example 1. Checking if Run as root First, we will create a script that checks whether the script file is run as the root user. This can be useful when writing scripts that require root privileges, such as installing packages as the root user. Create a file named check-for-root.sh: nano check-for-root.sh Use the following code to check for root user: #!/bin/bash if [[ $EUID -ne 0 ]]; then /usr/bin/printf "${R}>>>>${NC} Please run as root\n" exit 1 fi Grant the file execute permissions: chmod +x check-for-root.sh And run it: ./check-for-root.sh If the script is run as a regular user, the console will print the message "Please run as root". The check for the root user uses the condition $EUID -ne 0, where: $EUID is an environment variable that holds the numeric user ID. In Linux systems, the root user always has the ID 0, while other user accounts start at 1000. -ne is a comparison operator meaning "not equal". Instead of ne, you can also use !=. Script Example 2. Checking the Linux distribution Next, let's create another script that checks which Linux distribution is being used. If the script is run on Ubuntu, it will print the message "This is Ubuntu". If the script is run on any other Linux distribution, it will print "Not Ubuntu. You can run this script only on Ubuntu distributions". Create a file named check-for-distribution.sh: nano check-for-distribution.sh Use the following code: #!/bin/bash dist=`grep DISTRIB_ID /etc/*-release | awk -F '=' '{print $2}'` if [ "$dist" == "Ubuntu" ]; then echo "This is Ubuntu" else echo "Not Ubuntu. You can run this script only on Ubuntu distributions" fi Make the file executable: chmod +x check-for-distribution.sh And run it: ./check-for-distribution.sh If the script is run on an Ubuntu system, it will print "This is Ubuntu". On any other distribution, it will print "Not Ubuntu. You can run this script only on Ubuntu distributions". Script Example 3. Checking if File Exists Now, let’s look at another practical example. We will create a Bash script that checks if a file named file1.txt exists. If it doesn't exist, the script will create it. The script checks for the file in the same directory it is run. If the file already exists, the script will print a message without creating the file. Create a file named check-file.sh: nano check-file.sh Use the following script code: #!/bin/bash FILE="file1.txt" if [ ! -f "$FILE" ]; then touch "$FILE" echo "$FILE has been created." else echo "$FILE already exists." fi Grant execute permissions for the script: chmod +x check-file.sh Run the script: ./check-file.sh If the file1.txt file already exists in the directory from which the script is run, you will see the message "file1.txt already exists.". The file will not be created. Conclusion In this article, we reviewed the principles of logical statements such as if-else in the Bash shell and provided practical examples of using these statements. These examples are useful when writing scripts to automate system tasks or checks.
18 February 2025 · 7 min to read
Linux

Using the ps aux Command in Linux

Effective system administration in Linux requires constant awareness of running processes. Whether diagnosing performance bottlenecks, identifying unauthorized tasks, or ensuring critical services remain operational, the ps aux command is an indispensable tool.  This guide provides a comprehensive exploration of ps aux, from foundational concepts to advanced filtering techniques, equipping you to extract actionable insights from process data. Prerequisites To follow the tutorial: Deploy a Linux cloud server instance at Hostman SSH into the server instance Understanding Processes in Linux Before we explore the ps aux command, let's take a moment to understand what processes are in the context of a Linux system. What are Processes? A process represents an active program or service running on your Linux system. Each time you execute a command, launch an application, or initiate a background service, you create a process. Linux assigns a unique identifier, called a Process ID (PID), to each process. This PID allows the system to track and manage individual processes effectively. Why are Processes Grouped in Linux? Linux employs a hierarchical structure to organize processes. This structure resembles a family tree, where the initial process, init (or systemd), acts as the parent or ancestor. All other processes descend from this initial process, forming a parent-child relationship. This hierarchy facilitates efficient process management and resource allocation. The ps Command The ps (process status) command provides a static snapshot of active processes at the moment of execution. Unlike dynamic tools such as top or htop, which update in real-time, ps is ideal for scripting, logging, or analyzing processes at a specific point in time. The ps aux syntax merges three key options: a: Displays processes from all users, not just the current user. u: Formats output with user-oriented details like CPU and memory usage. x: Includes processes without an attached terminal, such as daemons and background services. This combination offers unparalleled visibility into system activity, making it a go-to tool for troubleshooting and analysis. Decoding the ps aux Output Executing ps aux generates a table with 11 columns, each providing critical insights into process behavior. Below is a detailed explanation of these columns: USER This column identifies the process owner. Entries range from standard users to system accounts like root, mysql, or www-data. Monitoring this field helps detect unauthorized processes or identify which users consume excessive resources. PID The Process ID (PID) is a unique numerical identifier assigned to each task. Administrators use PIDs to manage processes—for example, terminating a misbehaving application with kill [PID] or adjusting its priority using renice. %CPU and %MEM These columns display the percentage of CPU and RAM resources consumed by the process. Values above 50% in either column often indicate performance bottlenecks. For instance, a database process consuming 80% CPU might signal inefficient queries or insufficient hardware capacity. VSZ and RSS VSZ (Virtual Memory Size) denotes the total virtual memory allocated to the process, including memory swapped to disk. On the other hand, RSS (Resident Set Size) represents the physical memory actively used by the process. A process with a high VSZ but low RSS might reserve memory without actively utilizing it, which is common in applications that preallocate resources. TTY This field shows the terminal associated with the process. A ? indicates no terminal linkage, which is typical for background services like cron or systemd-managed tasks. STAT The STAT column reveals process states through a primary character + optional attributes: Primary States: R: Running or ready to execute. S: Sleeping, waiting for an event or signal. I: Idle kernel thread D: Uninterruptible sleep (usually tied to I/O operations). Z: Zombie—a terminated process awaiting removal by its parent. Key Attributes: s: Session leader N: Low priority <: High priority For example, a STAT value of Ss denotes a sleeping session leader, while l< indicates an idle kernel thread with high priority. START and TIME START indicates the time or date the process began. Useful for identifying long-running tasks. TIME represents the cumulative CPU time consumed since launch. A process running for days with minimal TIME is likely idle. COMMAND This column displays the command or application that initiated the process. It helps identify the purpose of a task—for example, /usr/bin/python3 for a Python script or /usr/sbin/nginx for an Nginx web server. Advanced Process Filtering Techniques While ps aux provides a wealth of data, its output can be overwhelming on busy systems. Below are methods to refine and analyze results effectively. Isolating Specific Processes To focus on a particular service—such as SSH—pipe the output to grep: ps aux | grep sshd Example output: root 579 0.0 0.5 15436 5512 ? Ss 2024 9:35 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups root 2090997 0.0 0.8 17456 8788 ? Ss 11:26 0:00 sshd: root@pts/0 root 2092718 0.0 0.1 4024 1960 pts/0 S+ 12:19 0:00 grep --color=auto sshd This filters lines containing sshd, revealing all SSH-related processes. To exclude the grep command itself from results, use a regular expression: ps aux | grep "[s]shd"  Example output: root 579 0.0 0.5 15436 5512 ? Ss 2024 9:35 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups root 2090997 0.0 0.8 17456 8788 ? Ss 11:26 0:00 sshd: root@pts/0 Sorting by Resource Consumption Identify CPU-intensive processes by sorting the output in descending order: ps aux --sort=-%cpu | head -n 10 Example output: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND mysql 1734280 0.4 36.4 1325172 357284 ? Ssl Jan30 87:39 /usr/sbin/mysqld redis 1424968 0.3 0.6 136648 6240 ? Ssl Jan18 112:25 /usr/bin/redis-server 127.0.0.1:6379 root 1 0.0 0.6 165832 6824 ? Ss 2024 5:51 /lib/systemd/systemd --system --deserialize 45 root 2 0.0 0.0 0 0 ? S 2024 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? I< 2024 0:00 [rcu_gp] root 4 0.0 0.0 0 0 ? I< 2024 0:00 [rcu_par_gp] root 5 0.0 0.0 0 0 ? I< 2024 0:00 [slub_flushwq] root 6 0.0 0.0 0 0 ? I< 2024 0:00 [netns] root 8 0.0 0.0 0 0 ? I< 2024 0:00 [kworker/0:0H-events_highpri] Similarly, you can sort by memory usage to detect potential leaks: ps aux --sort=-%mem | head -n 10 Example output: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND mysql 1734280 0.4 36.4 1325172 357284 ? Ssl Jan30 87:39 /usr/sbin/mysqld root 330 0.0 4.4 269016 43900 ? S<s 2024 22:43 /lib/systemd/systemd-journald root 368 0.0 2.7 289316 27100 ? SLsl 2024 8:19 /sbin/multipathd -d -s root 1548462 0.0 2.5 1914688 25488 ? Ssl Jan23 2:08 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock root 1317247 0.0 1.8 1801036 17760 ? Ssl Jan14 22:24 /usr/bin/containerd root 556 0.0 1.2 30104 11956 ? Ss 2024 0:00 /usr/bin/python3 /usr/bin/networkd-dispatcher --run-startup-triggers root 635 0.0 1.1 107224 11092 ? Ssl 2024 0:00 /usr/bin/python3 /usr/share/unattended-upgrades/unattended-upgrade-shutdown --wait-for-signal root 2090997 0.0 0.8 17456 8788 ? Ss 11:26 0:00 sshd: root@pts/0 root 2091033 0.0 0.8 9936 8480 pts/0 Ss 11:26 0:00 bash --rcfile /dev/fd/63 Real-Time Monitoring Combine ps aux with the watch command to refresh output every 2 seconds: watch -n 2 "ps aux --sort=-%cpu" This provides a dynamic view of CPU usage trends. Zombie Process Detection Zombie processes, though largely harmless, clutter the process list. Locate them with: ps aux | grep 'Z' Persistent zombies often indicate issues with parent processes failing to clean up child tasks. Practical Use Cases Now, let’s explore some common use cases of the ps aux command in Linux: Diagnosing High CPU Usage Follow the below steps: Execute this command to list processes by CPU consumption. ps aux --sort=-%cpu Identify the culprit—for example, a malfunctioning script using 95% CPU. If unresponsive, terminate the process gracefully with: kill [PID] Or forcibly with: kill -9 [PID] Detecting Memory Leaks Simply do the following: Sort processes by memory usage: ps aux --sort=-%mem Investigate tasks with abnormally high %MEM values. Restart the offending service or escalate to developers for code optimization. Auditing User Activity List all processes owned by a specific user (e.g., Jenkins): ps aux | grep ^jenkins This helps enforce resource quotas or investigate suspicious activity. Best Practices for Process Management Let’s now take a quick look at some best practices to keep in mind when managing Linux processes: Graceful Termination: Prefer kill [PID] over kill -9 to allow processes to clean up resources. Log Snapshots: Periodically save process lists for audits: ps aux > /var/log/process_audit_$(date +%F).log Contextual Analysis: A high %CPU value might be normal for a video encoder but alarming for a text editor. Hence, it’s essential to consider the context when making an analysis. Common Pitfalls to Avoid Here are some pitfalls to look out for when using ps aux in Linux: Misinterpreting VSZ: High virtual memory usage doesn’t always indicate a problem—it includes swapped-out data. Overlooking Zombies: While mostly benign, recurring zombies warrant investigating parent processes. Terminating Critical Services: Always verify the COMMAND field before using kill to avoid disrupting essential services. Conclusion The ps aux command is a cornerstone of Linux system administration, offering deep insights into process behavior and resource utilization. You can diagnose performance issues, optimize resource allocation, and maintain system stability by mastering its output interpretation, filtering techniques, and real-world applications.  For further exploration, consult the ps manual (man ps) or integrate process monitoring into automated scripts for proactive system management.
18 February 2025 · 9 min to read
Linux

How to Open Ports and List Open Ports in Linux

When working with networks in Linux, you may need to open or close a network port. Port management is essential for security — the fewer open ports in a system, the fewer potential attack vectors it has. Furthermore, if a port is closed, an attacker cannot gather information about the service running on that specific port. This guide will explain how to open or close ports as well as how to check open ports in Linux distributions such as Ubuntu/Debian and CentOS/RHEL using firewalls like ufw, firewalld, and iptables. It will also  We will demonstrate this process on two Linux distributions: Ubuntu 22.04 and CentOS 9, run on Hostman VPS. All commands provided here will work on any Debian-based or RHEL-based distributions. What is a Network Port? Ports are used to access specific applications and protocols. For example, a server can host both a web server and a database—ports direct traffic to the appropriate service. Technically, a network port is a non-negative integer ranging from 0 to 65535. Reserved Ports (0-1023): Used by popular protocols and network services like SSH (port 22), FTP (port 21), HTTP (port 80), and HTTPS (port 443). Registered Ports (1024-49151): These ports can be used by specific applications for communication. Dynamic Ports (49151-65535): These are used for temporary connections and can be dynamically assigned to applications. How to Open Ports in Debian-Based Linux Distributions On Debian-based systems (Ubuntu, Debian, Linux Mint, etc.), you can use ufw (Uncomplicated Firewall). ufw comes pre-installed on most popular APT-based distributions. To check if ufw is installed, run: ufw version If the version is displayed, ufw is installed. Otherwise, install it with: apt update && apt -y install ufw By default, ufw is inactive, meaning all ports are open. You can check its status with: ufw status To activate it, use: ufw enable You will need to confirm by entering y. Note that enabling ufw may interrupt current SSH connections. By default, ufw blocks all incoming traffic and allows all outgoing traffic. To check the default policy, use: cat /etc/default/ufw Opening Ports in ufw To open a port, use the command: ufw allow <port_number> For example, to open port 22 for SSH, run: ufw allow 22 You can list multiple port numbers separated by commas, followed by the protocol (tcp or udp): ufw allow 80,443,8081,8443/tcpufw allow 80,443,8081,8443/udp Instead of specifying port numbers, you can use the service name as defined in /etc/services. For example, to open the Telnet service, which uses port 23 by default: ufw allow telnet Note: You cannot specify multiple service names at once; ufw will return an error: To open a port range, use the following syntax: ufw allow <start_port>:<end_port>/<protocol> Example: ufw allow 8000:8080/tcp Closing Ports in ufw To close a port using ufw, use the command: ufw deny <port_number> For example, to close port 80, run: ufw deny 80 You can also use the service name instead of the port number. For example, to close port 21 used by the FTP protocol: ufw deny ftp Checking Open Ports in ufw To list all open and closed ports in the Linux system, use: ufw status Another option to view open ports in Linux is: ufw status verbose How to Open a Port in RHEL-Based Linux Distributions Linux RHEL-based distributions (CentOS 7+, RHEL 7+, Fedora 18+, OpenSUSE 15+) use firewalld by default. Opening Ports in firewalld To check if firewalld is installed, run: firewall-offline-cmd -V If the version is displayed, firewalld is installed. Otherwise, install it manually: dnf install firewalld By default, firewalld is disabled. Check its status with: firewall-cmd --state To enable firewalld, run: systemctl start firewalld To open port 8080 for the TCP protocol, use: firewall-cmd --zone=public --add-port=8080/tcp --permanent --zone=public: Specifies the zone for the rule. --add-port=8080/tcp: Specifies the port and protocol (TCP or UDP). --permanent: Saves the rule to persist after a system reboot. Without this parameter, the change will only last until the next reboot. Alternatively, you can open a port in Linux by specifying a service name instead of a port number. For example, to open the HTTP (port 80) protocol: firewall-cmd --zone=public --add-service=http --permanent Reload firewalld to apply the changes: firewall-cmd --reload Closing Ports in firewalld You can close a port using either its number or service name. To close a port using its number, run: firewall-cmd --zone=public --remove-port=8080/tcp --permanent To close a port using the service name, run: firewall-cmd --zone=public --remove-service=http --permanent After opening or closing a port, always reload firewalld to apply the changes: firewall-cmd --reload Listing Open Ports in firewalld To list all open ports in your Linux system, you can use: firewall-cmd --list-ports Managing Ports in iptables Unlike ufw and firewalld, iptables comes pre-installed in many Linux distributions, including Ubuntu, Debian, RHEL, Rocky Linux, and AlmaLinux. Opening Ports in iptables To open port 8182 for incoming connections, use: iptables -A INPUT -p tcp --dport 8182 -j ACCEPT -A INPUT: The -A flag is used to add one or more rules. INPUT specifies the chain to which the rule will be added (in this case, incoming connections). -p tcp: Specifies the protocol. Supported values include tcp, udp, udplite, icmp, esp, ah, and sctp. --dport 8182: Specifies the port to be opened or closed. -j ACCEPT: Defines the action for the port. ACCEPT allows traffic through the port. To open a port for outgoing connections, use the OUTPUT chain instead: iptables -A OUTPUT -p tcp --dport 8182 -j ACCEPT To open a range of ports, use the --match multiport option: iptables -A INPUT -p tcp --match multiport --dports 1024:2000 -j ACCEPT Closing Ports in iptables To close a port, use the -D option and set the action to DROP. For example, to close port 8182 for incoming connections: iptables -A INPUT -p tcp --dport 8182 -j DROP To close a range of ports, use the same syntax as for opening a range, but replace ACCEPT with DROP: iptables -A INPUT -p tcp --match multiport --dports 1024:2000 -j DROP Saving iptables Rules By default, iptables rules are only effective until you restart the server. To save the rules permanently, install the iptables-persistent utility. For APT-based distributions: apt update && apt -y install iptables-persistent For DNF-based distributions: dnf -y install iptables-persistent To save the current rules, run: iptables-save After the next server reboot, the rules will be automatically reloaded. Viewing Open Ports in iptables To list all current rules and opened ports on the Linux machine, use: iptables -L -v -n To list rules specifically for IPv4, use: iptables -S To list rules for IPv6, use: ip6tables -S Conclusion In this guide, we demonstrated how to open and close network ports in Linux and check currently open ports using three different utilities: ufw, firewalld, and iptables. Proper port management reduces the risk of potential network attacks and helps obscure information about the services using those ports.
14 February 2025 · 6 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support