Linux – ExpLinux https://explinux.com Explore Linux How to, Tutorials, Unix, Updates, Technology. Sun, 11 May 2025 17:08:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://explinux.com/wp-content/uploads/2023/04/cropped-favicon-32x32-1-32x32.png Linux – ExpLinux https://explinux.com 32 32 Variables in Bash Scripting: A Beginner’s Guide https://explinux.com/2023/08/variables-in-bash-scripting.html Tue, 01 Aug 2023 20:45:17 +0000 https:/?p=895 Variables in Bash Scripting: A Beginner’s Guide
Variables in Bash Scripting A Beginners Guide Variables in Bash Scripting
Variables in Bash Scripting: A Beginner’s Guide

As a newbie to the world of Linux and scripting, understanding the concept of variables in Bash scripting can be both essential and intriguing. Variables play a fundamental role in storing and manipulating data within a script, allowing you to create dynamic and interactive scripts. Always use variables in the script to make your life easier. In this article, we’ll learn the basics of variables in Bash scripting, how to declare the variable in Bash scripting and use it, and interactive examples with commands to help you grasp the concept effectively.

If you are new to bash script read: How to write your first bash script

What are Variables in Bash Scripting?

In any programming, a variable is a symbolic name or identifier that represents a value or data stored in the computer’s or server’s memory. Variables act as containers that hold different types of information, such as numbers, text, filenames, and more. In Bash scripting, variables enable you to store values temporarily in memory and reference them throughout your script and you can use the same multiple times because Bash is dynamically typed, making it easier to work with data dynamically.

Declaring Variables in Bash

In Bash, declaring a variable is as simple as assigning a value to it with a “=” sign. There are no data types required when declaring a variable; Bash automatically determines the type based on the context. To declare a variable in bash, use the below syntax:

variable_name=value

For example, to store the value “Hello, Explinux!” in a variable called as below example :

greeting="Hello, Explinux!"

Remember that there should be no spaces around the equal sign when declaring a variable in Bash scripting. For string use “” and number you can use 1 or any number without “”.

Using Variables in Bash

Once we have declared a variable, you can use it throughout your script by referencing its name with a dollar sign ($). For example, to print the value of the greeting variable which we have declared before, you can use the echo command:

greeting="Hello, Explinux!"
echo $greeting

The output of the script will be when you run it :

Hello Explinux!

Using the dollar sign ($) before the variable name in the script tells Bash to substitute the variable with its value during execution.

Commands with Variables

Variables in Bash are not limited to static values; they can also hold the output of commands and that is useful to write automation scripts. By enclosing the Linux command in backticks (`) or using the $() syntax, you can capture the command’s output and store it in a variable.

Example: Command Output in a Variable

#!/bin/bash
# Command Output in a Variable

# Store the current date in a variable using backticks
current_date=`date`

# Print the value of the variable
echo "Current Date: $current_date"

In this above example, the date command retrieves the current date, and we store the output in the current_date variable. The echo command then displays the value of the current_date variable in the terminal, showing the current date when the script is run.

Example: Command Output in a Variable with $()

#!/bin/bash
# Command Output using $() in a Variable.

# Store the output of the 'ls' command in a variable using $()
files=$(ls)

# Print the value of the variable
echo "Files in the current directory: $files"

Here, the ls command lists the files in the current directory where the script is executed. We use the $() syntax to capture the output of the ls command and store it in the files variable. The echo command then displays the stored value of the files variable, after execution, it will show the list of files in the directory.

Rules for Naming Variables

When naming variables in Bash scripting, you need to follow certain rules to define variables:

  1. Variable names must begin with an alphabetic letter (a-z or A-Z) or an underscore (_).
  2. After the first character, variable names can also include digits (0-9).
  3. No spaces are allowed in variable names in the bash script.
  4. Variable names are case-sensitive. For example, greeting and Greeting are considered two different variables. This is due to Linux also case sensitive.

Arithmetic with Variables

Performing arithmetic operations in Bash scripting is a good example to learn variables. Let’s see an example of how to use variables for arithmetic:

#!/bin/bash
# Arithmetic with Variables

# Declare two variables
num1=10
num2=5

# Perform arithmetic operations
sum=$((num1 + num2))
difference=$((num1 - num2))
product=$((num1 * num2))
quotient=$((num1 / num2))

# Print the results
echo "Sum: $sum"
echo "Difference: $difference"
echo "Product: $product"
echo "Quotient: $quotient"

In this example, we declare two variables num1 and num2 and perform various arithmetic operations (addition, subtraction, multiplication, and division) using these two variables. The output will be using the echo command, demonstrating how variables can store and manipulate data in Bash script.

Accepting User Input as Variable

Variables are also useful for accepting user input and processing or manipulating it in the script. Let’s see below a simple script example that takes the user’s name as input and greets them:

#!/bin/bash
# Accept User Input and Greet

# Ask the user for their name
read -p "Enter your name: " name

# Greet the user with variable name($name)
echo "Hello, $name! Nice to meet you."

In this script, we use the read command to prompt the user for their name and store the input in the name variable. The entered name by the user is then used in the greeting message when the script is executed. This is just an example you can use commands as well or any other input.

Conclusion

Variables are the building blocks of Bash scripting, enabling you to store, manipulate, and interact with data dynamically. With the knowledge of how to declare and use variables, you can create more flexible and powerful Bash scripts. Remember the basic syntax for declaring variables, use the dollar sign ($) to reference their values, and follow the rules for naming variables.

As you continue your journey into the world of Bash scripting, the understanding of variables will become more crucial as you explore advanced concepts like loops, conditionals, and functions. Practice creating scripts that utilize variables in various scenarios, and you’ll soon gain confidence in your ability to develop efficient and functional Bash scripts to automate tasks and enhance your productivity. Happy scripting

]]>
How to Write and Run First Bash Script https://explinux.com/2023/08/how-to-write-first-bash-script.html Mon, 31 Jul 2023 20:52:28 +0000 https:/?p=879 How to Write and Run First Bash Script
How to Write and Run First Bash Script

If you’re new to the world of Linux Administration and scripting, writing your first Bash script might seem intimidating. However, fear not! Bash scripting is a very beginner-friendly way to automate tasks and interact with the command-line interface, it is the first step to automation. In this article, we’ll guide you through the process of writing and running your very first Bash script.

Read More : Introduction to Bash scripting

Getting Started

To begin, open a text editor on your system. You can use your favorite plain text editor like vi or nano.

If you do not know VI editor read: How to use vi editor

Write the First Bash Script

In the text editor, type the following lines to create your Hello World Bash script:

If you are using vi editor give the name with .sh extension. Like below example

  • # vi hello_world.sh

#!/bin/bash
# This is a simple Hello World Bash script
echo "Hello, World!"

Let’s understand the code :

#!/bin/bash: The first line is called the “shebang,” which tells the system to use the Bash interpreter to run the script. It ensures that the bash script is executed using the correct shell. Sometimes it can be changed if you are using a customized system otherwise it will be the same for all Linux systems.

# This is a simple Hello World Bash script: This line is a comment. Comments start with the # symbol and are ignored by the Bash interpreter. They provide useful information to user or if you share the script with some other guy this will tell about the script’s purpose and help understand the code.

echo "Hello, World!": The command echo in Linux Bash is used to display messages on the terminal or shell. Our script will print “Hello, World!” when the script is executed. In this place, you can use any command like ls, df -h, or any it will run.

Save the Script

After writing the script, save the bash script with a meaningful name and the .sh extension. For example, you can save it as hello_world.sh in our case. If you are using vi or nano then we may have already given it a meaningful name and saved it with press the esc button and writing “:wq!” press enter key.

Make the Script Executable

Before running our bash script, we need to make it executable. Open your terminal or command prompt and navigate to the directory where you saved the script or you have to provide the path as well with the script. Then, use the following chmod command to give execute permissions to the script:

# chmod +x hello_world.sh

The chmod command changes file permissions, you can use the man command to check more usages and +x makes the script executable for the current user.

Run the Script

From the above action, your script is now executable, it’s time to run it! In the terminal or command prompt shell, enter the below command:

./hello_world.sh

or

sh hello_world.sh

The ./ before the script name specifies the current directory and default shell, and then the script name is provided. sh is also to tell the script is a shell script and runs from the default shell. Press Enter to run script , and you should see the output:

Hello, World!

Congratulations! You have successfully written and run your first Hello World Bash script journey. Now you are one step ahead.

Troubleshooting

If you encounter any issues running the bash script, follow the below steps to troubleshooting :

  • The shebang (#!/bin/bash) is the first line of the bash script.
  • The bash script file should have the .sh extension.
  • The script has to execute permissions (use chmod +x) or use chmod u+x script name.
  • You are running the script from the correct directory (use ./ before the script name). If not give a full path like ./home/username/hello_world.sh.

Conclusion

Writing and running your first Hello World Bash script is an exciting milestone in your journey as a Linux automation programmer. With this basic foundation, you can continue exploring Bash scripting and its many possibilities to automate tasks and reduce manual errors. As you gain more experience with time, you’ll find yourself creating powerful scripts to automate tasks and streamline your workflow. So keep practicing, experiment with different commands in place of echo, and embrace the world of Bash scripting! Happy scripting!

]]>
Introduction to Bash Scripting – An Essential Part of Administration https://explinux.com/2023/08/introduction-to-bash-scripting.html Mon, 31 Jul 2023 19:33:37 +0000 https:/?p=868 Introduction to Bash Scripting
Introduction to Bash Scripting Variables in Bash Scripting

Bash scripting is a powerful tool for system administrators that allows users to automate repetitive tasks, automate workflows, and perform complex operations in a command-line environment. If you’ve never worked with bash scripting before, it might seem daunting at first, but if you are familiar with Linux basics then with a little guidance, you can quickly grasp the fundamentals and start harnessing the full potential of the Bash shell scripting. Let’s start your journey of Bash scripting.

If you interested in Linux Directory Structure

What is Bash Scripting?

Bash, short for “Bourne Again Shell,” is a Unix shell and cli language that provides an interface for users to interact with the Linux operating system. Bash scripting involves writing a series of Linux commands, often referred to as a script, to be executed by the Bash shell. These scripts are essentially small programs that can automate tasks or perform various operations on the system- to reduce task time and manual errors. If you are using a Linux Operating system it is already prebuilt and no third-party installation or setting is required. If you are able to run the command you will able to use bash script.

For example, let’s start with  “Hello, World!” to the terminal:

#!/bin/bash
# This is a simple Bash script
echo "Hello, World!"

Save the above code in a file named hello_world.sh and make this script executable with chmod +x hello_world.sh. Then, run the script using ./hello_world.sh or sh hello_world.sh. The output “Hello, World!” will be displayed on the terminal.

Getting Started with Bash Variables

Variables in any script are used to store data that can be later manipulated or referenced in the script. They are for holding information that changes throughout the script’s execution. Likely a dynamic script it can be defined before use

Below example of using variables to greet a user:

#!/bin/bash
# Example of using variables use in bash script 
name="explinux"
echo "Hello, $name! How are you today?"

Save the above code in a file named greeting.sh and make this script executable with chmod +x greeting.sh. Then, run the script using ./greeting.sh or sh greeting.sh. The output “Hello, explinux! How are you today?” will be displayed on the terminal. Where $name is replaced with the value we have stored in the variable.

Conditional Statements in Bash

Conditional statements allow you to make decisions in our automation script based on given certain conditions like other programming languages. The most commonly used conditional for any script statement in Bash is the if statement which is similar to any other programming language. Only the written part is different we need to tell where the condition ends.

Let’s create a script that checks if a number is positive or negative with the bash script :

#!/bin/bash
# Example of using conditional statements
read -p "Enter a number: " num

if [ $num -gt 0 ]; then
    echo "The number is positive."
elif [ $num -lt 0 ]; then
    echo "The number is negative."
else
    echo "The number is zero."
fi

Save the above code in a file named positive_negative_check.sh, make it executable, and then run the script as we did in the above examples. Enter a number, and the script will display whether the number is positive, negative, or zero.

Looping in Bash

Loops are used to repeat a set of commands or functions multiple times. In Bash, we have for and while loops to achieve this loop condition.

For example, let’s create a script that prints numbers from 1 to 5 using a for loop:

#!/bin/bash
# Example of using a for loop
for i in {1..5}; do
    echo "Number: $i"
done

Save the above code and name it number_loop.sh, make it executable with chmod -x number_loop.sh , and then run the script sh number_loop.sh or ./number_loop.sh. We will see the output with numbers from 1 to 5 printed on the terminal.

Conclusion

Bash scripting is a valuable skill for every Linux admin or Linux automation engineer. With just learning the basics of Bash scripting, we can enhance our productivity, automate tasks, and simplify complex operations on our systems. We covered the essential concepts of Bash scripting, including creating scripts, using variables, implementing conditional statements, and employing loops. With this foundation, you can start playing with Bash scripting. We have a full list or articles on bash scripting check those out to learn more. So, start scripting, and enjoy the power of automation!

]]>
100 Best Use Cases of Find Command in Linux -ExpLinux https://explinux.com/2023/02/100-use-of-find-command-in-linux.html Mon, 20 Feb 2023 20:05:50 +0000 https://explinux.online/?p=794 Find Command In Linux
Find Command in Linux
Find Command in linux

The very popular Linux admins friend find command in Linux was created as a part of the Unix operating system by Ken Thompson and Dennis Ritchie at Bell Labs in the golden era of new computer development in the 1970s. Thompson and Ritchie were two of the pioneer developers of the Unix operating system and also developed the mother of most programming language C programming language, C is mostly used for developing software for Unix-based systems. The find command in Linux and Unix operating systems is still widely used today for searching for files and directories on a system and performing operations on them.

Some Alternatives of Find Command

Related Post: MV Command

22 Most Useful Linux Commands

15 Linux Commands to Boost Productivity

Master Guide to Vi Editor

There are only locate is main alternatives to the find command in Linux, which gives it some competition but we have added 4 more alternatives that can be useful in specific tasks.

locate: The locate command is the fastest way to search for files and directories on a Linux system. Unlike the find command, locate command creates its database of file paths that are generated periodically, so it provides faster results than find but it may not always be up to date. It will not come default in the system we have to install it and before first use has to update the Database of locate command. Update duration will depend upon your system file number.

grep: The grep command is an awesome tool for searching for patterns in text files. It can also be used to search for files and directories by name, although it is not as versatile as the find command in Linux because it searches only in text files.

whereis: The whereis command in Linux is used to locate the binary, source, and manual page files for a specified command. It is a simple but useful tool that provides basic information about a command, including its all locations on the system. for example command may be in /bin/ /sbin/ or /usr/bin/ it will show all.

which: The which command is in Linux is also used to locate the binary for a specified command. Unlike whereis, it only provides the location (bin /usr/bin, etc) of the executable file for the command for your bash profile and does not provide information about its source code or manual pages.

findmnt: The findmnt command in Linux is used to find and display information about mounted file systems on a Linux and Unix system. It provides information about the mounted file system type, source, and target mounted on for each mounted file system.

These are some alternatives but the find command is still on top because it gives you real-time all details of the file and provides the ability to perform operations even in the script you can use the find command to get currently accurate results and perform operations on the right file.

Top 100 Use Cases of Find Command

Please find below examples

SNUseCommand
1Find files in a specific directory:find /path/to/directory -type f
2Find directories in a specific directory:find /path/to/directory -type d
3Find files with a specific name:find /path/to/directory -name “file_name”
4Find files with a specific extension:find /path/to/directory -name “*.extension”
5Find files based on their size:find /path/to/directory -size +10M
6Find files based on their modification time:find /path/to/directory -mtime +7
7Find files based on their access time:find /path/to/directory -atime +7
8Find files based on their inode number:find /path/to/directory -inum 123456
9Find files that are readable:find /path/to/directory -perm -444
10Find files that are writable:find /path/to/directory -perm -222
11Find files that are executable:find /path/to/directory -perm -111
12Find files that are owned by a specific user:find /path/to/directory -user user_name
13Find files that are owned by a specific group:find /path/to/directory -group group_name
14Find files with a specific user ID:find /path/to/directory -uid 123456
15Find files with a specific group ID:find /path/to/directory -gid 123456
16Find files that match a specific pattern:find /path/to/directory -regex “.*pattern.*”
17Find files that contain a specific word or phrase:find /path/to/directory -type f -exec grep -q “word or phrase” {} \; -print
18Find files that are symbolic links:find /path/to/directory -type l
19Find files that are hard links:find /path/to/directory -type f -links +1
20Find files that are empty:find /path/to/directory -empty
21Find files that are not empty:find /path/to/directory ! -empty
22Find files and execute a specific command on each file:find /path/to/directory -type f -exec command {} \;
23Find files and move them to a new location:find /path/to/directory -type f -exec mv {} /path/to/new/location \;
24Find files and delete themfind /path/to/directory -type f -exec rm -i {} \;
25Find files and copy them to a new location:find /path/to/directory -type f -exec cp {} /path/to/new/location \;
26Find files and change the permissions on each file:find /path/to/directory -type f -exec chmod 755 {} \;
27Find files and change the owner of each file:find /path/to/directory -type f -exec chown user:group {} \;
28Find files and change the group of each file:find /path/to/directory -type f -exec chgrp group_name {} \;
29Find files and print the full path of each file:find /path/to/directory -type f -printf “%p\n”
30Find files and print the size of each file:find /path/to/directory -type f -printf “%s\n”
31Find files and print the inode number of each file:find /path/to/directory -type f -printf “%i\n”
32Find files and print the modification time of each file:find /path/to/directory -type f -printf “%T@\n”
33Find files and print the user name of the owner of each file:find /path/to/directory -type f -printf “%u\n”
34Find files and print the group name of the owner of each file:find /path/to/directory -type f -printf “%g\n”
35Find files and print the permissions of each file:find /path/to/directory -type f -printf “%M\n”
36Find files and execute a command with a specific time limit:find /path/to/directory -type f -mmin +5 -exec command {} \;
37Find files and execute a command only if the file has been modified in the last 5 minutes:find /path/to/directory -type f -mmin -5 -exec command {} \;
38Find files and execute a command only if the file has not been modified in the last 5 minutes:find /path/to/directory -type f ! -mmin -5 -exec command {} \;
39Find files and search for a specific string in each file:find /path/to/directory -type f -exec grep “string” {} \;
40Find files and list only the first 10 files that match a specific criteria:find /path/to/directory -type f -print | head -10
41Find files and list only the last 10 files that match a specific criteria: find /path/to/directory | head 10
42Find files and exclude a specific directory from the search:find /path/to/directory -type f -not -path “/path/to/directory/to/exclude/*” -print
43Find files and exclude multiple directories from the search:find /path/to/directory -type f \( -not -path “/path/to/directory/to/exclude/*” -and -not -path “/path/to/directory/to/exclude2/*” \) -print
44Find files and search for files with a specific name pattern:find /path/to/directory -type f -name “*.txt”
45Find files and search for files with a specific size:find /path/to/directory -type f -size +100M
46Find files and search for files smaller than a specific size:find /path/to/directory -type f -size -100M
47Find files and search for files larger than a specific size:find /path/to/directory -type f -size +100M
48Find files and search for files of an exact size:find /path/to/directory -type f -size 100M
49Find files and search for files with a specific user owner:find /path/to/directory -type f -user user_name
50Find files and search for files with a specific group owner:find /path/to/directory -type f -group group_name
51Find files and search for files with a specific type of permissions:find /path/to/directory -type f -perm 644
52Find files and search for files that are writable:find /path/to/directory -type f -perm -222
53Find files and search for files that are readable:find /path/to/directory -type f -perm -444
54Find files and search for files that are executable:find /path/to/directory -type f -perm -111
55Find files and search for files with specific type of executability:find /path/to/directory -type f -perm /u=x,g=x
56Find files and search for files that have changed in the last 7 days:find /path/to/directory -type f -ctime -7
57Find files and search for files that have changed more than 7 days ago:find /path/to/directory -type f -ctime +7
58Find files and search for files that have been modified in the last 7 days:find /path/to/directory -type f -mtime -7
59Find files and search for files that have been modified more than 7 days ago:find /path/to/directory -type f -mtime +7
60Find files and search for files that have been accessed in the last 7 days:find /path/to/directory -type f -atime -7
61Find files and search for files that have not been accessed in the last 7 days:find /path/to/directory -type f -atime +7
62Find files and search for files that match multiple criteria:find /path/to/directory -type f \( -name “*.txt” -or -name “*.pdf” \) -and -size +100M
63Find files and delete the files that match certain criteria:find /path/to/directory -type f -name “*.bak” -delete
64Find files and print the output in a specific format:find /path/to/directory -type f -printf “%p %u %g %s\n”
65Find files and execute a specific command on the matching files:find /path/to/directory -type f -exec chmod 644 {} \;
66Find files and limit the number of results to display:find /path/to/directory -type f -print | head -10
67Find files and sort the results by file size:find /path/to/directory -type f -printf “%s %p\n” | sort -nr
68Find files and exclude specific files or directories from the results:find /path/to/directory -type f \( ! -name “*.bak” ! -path “/path/to/directory/to/exclude/*” \) -print
69Find files and search for files based on their inode number:find /path/to/directory -type f -inum 123456
70Find files and search for files based on their access time and modification time:find /path/to/directory -type f -anewer file.txt -or -mnewer file.txt
71Find files and search for files with a specific type of type:find /path/to/directory -type l -ls
72Find files and search for files with a specific type of type and perform an action on them:find /path/to/directory -type l -exec ls -l {} \;
73Find files and search for files based on the number of links:find /path/to/directory -type f -links +5
74Find files and search for files based on the number of links and perform an action on them:find /path/to/directory -type f -links +5 -exec ls -l {} \;
75Find files and search for files based on the type of file system they are on:find /mnt/c/ -type f -fstype xfs
76Find files and search for files with a specific owner:find /path/to/directory -type f -user username
77Find files and search for files with a specific group:find /path/to/directory -type f -group groupname
78Find files and search for files with a specific permissions:find /path/to/directory -type f -perm 0644
79Find files and search for files with a specific name and perform a certain action on them:find /path/to/directory -type f -name “*.log” -exec gzip {} \;
80Find files and search for files that match a certain pattern and perform a certain action on them:find /path/to/directory -type f -regex “.*\.\(jpg\|jpeg\|png\)” -exec cp {} /path/to/destination/ \;
81Find files and search for files that have been modified in the last 7 days and perform a certain action on them:find /path/to/directory -type f -mtime -7 -exec rm {} \;
82Find files and search for files that have a specific size and perform a certain action on them:find /path/to/directory -type f -size +100M -exec mv {} /path/to/destination/ \;
83Find files and search for files that have a specific size range and perform a certain action on them:find /path/to/directory -type f -size +10M -size -100M -exec cp {} /path/to/destination/ \;
84Find files and search for files that have a specific size range and print the results in a specific format:find /path/to/directory -type f -size +10M -size -100M -printf “%p %u %g %s\n”
85Find files and search for files that have a specific name and move them to a specific location:find /path/to/directory -type f -name “*.log” -exec mv {} /path/to/destination/ \;
86Find files and search for files that have a specific name and copy them to a specific location:find /path/to/directory -type f -name “*.log” -exec cp {} /path/to/destination/ \;
87Find files and search for files that have a specific name and count the number of matches:find /path/to/directory -type f -name “*.log” | wc -l
88Find files and search for files that have a specific name and delete the matches:find /path/to/directory -type f -name “*.log” -delete
89Find files and search for files that have a specific name and rename the matches:find /path/to/directory -type f -name “*.log” -exec mv {} {}.bak \;
90Find files that have been modified in the last day and delete them:find /path/to/directory -type f -mtime -1 -delete
91Find files that have been modified in the last 7 days and compress them:find /path/to/directory -type f -mtime -7 -exec gzip {} \;
92Find files that have a specific name and show the details in a human-readable format:find /path/to/directory -type f -name “*.log” -exec stat -c “%n %s %y” {} \;
93Find all symbolic links and delete them:find /path/to/directory -type l -delete
94Find all symbolic links and replace them with their targets:find /path/to/directory -type l -exec sh -c ‘ln -sf “$(readlink -f “$1″)” “$1″‘ _ {} \;
95Find all symbolic links that point to a specific location and delete them:find /path/to/directory -type l -lname “/path/to/link/target” -delete
96Find all files that are larger than a specific size and delete them:find /path/to/directory -type f -size +100M -delete
97Find mp3 files in ext4 filesystemfind /mnt/usb/ -type f -fstype ext4 | grep -i ‘\.mp3$’
98Find files that have been modified in the last hour and move them to a different location:find /path/to/directory -type f -mmin -60 -exec mv {} /path/to/destination/ \;
99Find commnad in linux with sed command . Find file and replace text mylinux to explinuxfind my_files -type f -name ‘*.txt’ -exec sed -i ‘s/mylinux/explinux/g’ {} \;
100Find process pid status and print from proc find /proc/1234 -maxdepth 0 -name status -o -name stat -exec cat {} \;
Find Command in Linux – explinux

Feel free to provide you advice and a new or effective way to use the find command in Linux.

Conclusion:

Here we have seen 100 use cases of the find command in Linux and this can be used in a script or in daily use of system admin and troubleshooting tasks using the find command.

]]>
A Comprehensive Guide to the “mv” Command for Renaming Files in Linux 2023 https://explinux.com/2023/01/command-for-renaming-files-in-linux.html Thu, 19 Jan 2023 19:36:19 +0000 https://explinux.online/?p=784 Renaming files in Linux is an important part of basic file management. mv command was written by Ken Thompson. With the “mv” command, you can quickly and easily rename your files in a few simple steps. This guide provides a step-by-step overview of the process so you can get organized fast!

Renaming Files in Linux

Understand the Basics of the mv Command

The “mv” command is an abbreviation for “move” and is used to rename files or directories in Linux. By using the syntax mv Old_Filename New_Filename, you can move a target file or folder from its current location to a new location you specify. This command also allows you to rename files or folders by simply specifying the same source and destination. This is the most common and useful command for all Linux administrators.

Related article: 22 Linux Commands you should learn now

Move and Rename Files at Once With mv

In addition to renaming files, you can use the mv command to move a file by simply combining both a relocation and naming action into one command. For example, if you have a file called “mysecrete.txt” which is currently in the current working directory and want to move it to the “TopSecrete” folder and rename it as “mynewsecrete.txt”, all you need to do is use the below command:

# mv mysecrete.txt /TopSecrete/mynewsecrete.txt 

or If you want to rename on the same directory just use the below command :

# mv mysecrete.txt mynewsecrete.txt

This way, you will be able to move and rename your file in one simple step!

Move Only When Source File is Newer

The mv command offers the option to move only newer source files because sometimes we move files and it rewrites on an existing file, So in case to avoid this situation, we can use the -u option. This is useful in case of backup or backup script and could save your time by not moving unnecessary files, use this command:

# mv -u myimportantfile.txt importantSubdirectory/

Copy a File Directory and Its Contents Using mv

You can copy a file or directory and all its content (subdirectories and files) using the mv command. To do this, simply give the directory name to your command to move the directory to another directory with all data. For example, as shown above you could use as below :

# mv olddirectory Subdirectory/

If you want to move only “olddirectory” content to a Subdirectory use * at end of the directory, it will loop through all contents of the directory and move it and the directory will be empty.

# mv olddirectory/* Subdirectory/

Interactive mv Command for Rename File

mv command never as before rename but in case we want to give confirmation before renaming or moving a Linux file we can use -i (interactive) with the mv command.

If this is the new file and no overwrite then it will rename and move the file without any prompt.

# mv -i myfile.txt yourfile.txt

It will not ask for any confirmation if yourfile.txt does not exist.

But in case of files exist with the same name. So each time before overwriting the file in Linux or moving, IT will prompt for confirmation we can enter “y” or “n” respectively to accept and reject

# # mv -i myfile.txt yourfile.txt
mv: overwrite ‘yourfile.txt’? 

It will ask for your confirmation and you can provide your input with “y” or “n” in small letters.

Alternatives of mv Commands

There are many other functions we can perform with other commands too like renaming the “rename” command but this is not installed by default.

“cp” Command to copy files but the original file will not be renamed or moved.

“rsync” and “scp” commands also copy files and we can rename them in the destination folder. These commands are basically used for the remote server’s file copy and sync.

Conclusion

In this article, we have learned how to rename files in Linux with the help of the mv command. Even we have seen some more use cases of the mv command with alternatives that we can think of performing the same kind of operation. But alternatives will keep the source file too.

Hope this helps you understand how to file rename in Linux

]]>
We Asked 10 Linux Questions to ChatGPT and We Got Amazing Answers https://explinux.com/2023/01/10-linux-questions-to-chatgpt.html Wed, 18 Jan 2023 08:22:38 +0000 https://explinux.online/?p=751 We Asked 10 Linux Questions to ChatGPT and We Got Amazing Answers

What is ChatGPT

If you are very busy and still did not hear about this internet buzz or you see it but did not actually know what it then we are here to tell you.
ChatGPT is a language model developed by OpenAI, it is one of the many AI chatbots of its kind, there are other AI models such as GPT-2 (a predecessor of ChatGPT) developed by OpenAI and other companies like Google, Microsoft, Amazon, and IBM have also developed similar models. Whenever you chat or mail to google or Microsoft every time the chatbot replies to your general queries, only in case of escalation humans are involved.

The inspiration behind the creation of ChatGPT and other AI models like it is to create a machine that can understand and generate human-like text. These models are based on a neural network architecture called the transformer, which has shown to be very effective at natural language processing tasks such as language translation, text summarization, and question answering.

The idea behind creating such models is to make the computer understand human language more efficiently so that it can be used in various industries like customer service, content creation, and more. These models are also being used to improve the accuracy and efficiency of machine learning models in a wide range of applications such as speech recognition, natural language understanding, and others.

Additionally, OpenAI’s goal is to advance AI in a way that is safe for humanity and to provide the most powerful AI technologies to those who will use them to benefit humanity. OpenAI aims to make this available to everyone so that the benefits of AI can be widely distributed.

Who Owns OpenAI?

Elon Musk, Sam Altman,Wojciech Zaremba, Ilya Sutskever,and , Greg Brockman founded OPENAI in 2015 . ELON musk stepped out in 2018 and the current CEO is Sam Altman. The most important event is that Microsoft invested 1 Billion dollars in OpenAI, Maybe in the future, you can see OpenAI features in your Windows Office applications

You may be Interested : Most Important 22 Linux Commands

We have asked 10 Linux questions to ChatGPT, and let’s see how amazing it’s answered it. Did ChatGPT able to clear the Linux System Admin interview?

10 Questions to ChatGPT

Create a User and the password expire in 60 days.

Create user with ChatGPT

ChatGPT has done good work and is able to give the correct answer to this basic question. So one point to ChatGPT.

How to delete User with home directory?

Delete user with help of chatgpt

ChatGPT again did good work it will help you delete the home directory of a user with the user account in Linux. For this question, you don’t need to go to StackOverflow. One point to this AI chatbot.

How to Troubleshoot SSH issues?

troubleshoot ssh issue with chatgpt Variables in Bash Scripting

Ohh here we are quite disappointed with ChatGPT’s answer because we all know “systemctl status ssh” will give us an error that ssh. service not found. The correct command is “systemctl status sshd“. We are disappointed because if a person with a beginner level works on this then he could try the second step to install the ssh server and in case ssh is installed he will be quite confused that why it not showing service available . The steps provided by ChatGPT AI is quite basic and maybe if we ask the second time we get other options but we have tried once and in one go we got basic steps.

So in this case 0 points to ChatGPT.

How to formate a 4TB harddisk ?

formate 4TB disk using chatgpt Variables in Bash Scripting

This is a trick question we have asked here ChatGPT failed to give the right answer. If you get what is wrong in this then congrats you are working on a good data center or Big project. If you are thinking about what is wrong with this then let me tell you above 2TB drive we have to use parted command otherwise you will get the error.

So 0 points to ChatGPT on this trick question.

Related : How to use parted command ?

how to create 500 GB LVM from 1 TB raw device in RedHat Linux?

Create LVM using chatgpt
Create lvm pvs and vgs using chatgpt

Awesome now as expected we have got out the correct answer from this popular AI chatbot. You can just copy and paste commands to create LVM in Linux just you need to change names as per your device and requirements.

Again ChatGPT has gained 1 more point.

How to extend 16 TB ext4 LVM to 24 TB in Redhat Linux?

Variables in Bash Scripting

Again ChatGPT failed in the trick question if you know then you are a good Linux Engineer. The issue is that we can not increase the ext4 partition by more than 16TB. After 16TB we have to use the xfs partition. So running all those commands will not give you any results.

Zero points to our ChatGPT

How to change all new user’s home directory in /newhome when we create users by default in Redhat Linux?

Create new home for new user using chatgpt

I think ChatGPT is very good at user management, So you can ask any question related to user management and just follow it because we got again the right answer.

One more point to ChatGPT.

Create a bash script to delete files from /tmp folder which is older than 60 days in RedHat Linux.

delete 60 days files from tmp using chatgpt Variables in Bash Scripting

This is just a simple script but it did a good job. For old system admins who use the “-exec rm -f {} \;” newer versions of the find command introduce -delete. So we can say that ChatGPT knows the new find command.

We have tried a simple bash script you can check with the complex script, if you like this article then we will ask ChatGPT other bash script questions.

We have to give 1 point to ChatGPT

How to restrict the root to delete the specific file?

make file not delete with chatgpt
Restrict root to delete file part2 using chatgpt Variables in Bash Scripting

This time ChatGPT shows us that it is just an AI, we all know we can not restrict root like that this could be possible partially but not 100% secure. The only two ways to restrict root are to change attribute and use SELinux which can also restrict root until the root user figure out what the issue is.

In our case, we will 0 points to ChatGPT. If you want to try and give more points let us know in the comments.

Related : What is Selinux ?

How to Disable Selinux ?

Create an NFS service dependent on /sanstorage mount point in Redhat Linux.

Nfs server help of chatgpt
Nfs server with dependency part2 with chatgpt Variables in Bash Scripting
NFS server with help of chatgpt with dependency

In this answer, we will give .5 marks to OpeAI chatbot because there are some other methods that we are using to create dependency for NFS and other services. That is correct but anyone can disable this service and start nfsd service.

So .5 for this answer.

Result

The final result for our question answer session of ChatGPT has got 5.5/10.

5.5/10

Conclusion

As we have seen ChatGPT is accurate to do simple and basic level quetions. But when we tried some trick question this AI chatbot is unable to give answers. As per our question answer we see for local user mangement tasks we can just copy paste but for other task we need to rely on our knowledge. For for the level 1 Job you can use ChatGPT with little guidence. ChatGPT is still learning let see when it cross L2 and L3 level.

Hope this will give you a good idea about OpenAI chatbot.

]]>
Python Script To SSH and Run Multiple Commands in Linux – Save hours in less than 80 lines https://explinux.com/2023/01/python-script-to-ssh-and-run-commands.html Fri, 06 Jan 2023 23:48:28 +0000 https://explinux.online/?p=722 Python Script To ssh and Run Multiple Commands in Linux

Every Linux admin wants a python script to ssh and runs multiple commands in Linux. Here we will show and give a python script to run multiple commands on multiple servers and get output in excel.

Python Script To SSH and Run Multiple Commands in Linux - Save hours in less than 80 lines

To run commands by ssh over remote Linux servers python module used is as paramiko and by using paramiko we can run commands on remote Linux servers and even we get output and error messages. So let’s start with the script.

What is Paramiko?

Paramiko is a Python library that provides a means of securely and remotely connecting to and interacting with a device using the SSH (Secure Shell) protocol. It is often used for automating tasks, such as deploying software updates or gathering data from remote servers. Paramiko supports a number of authentication protocols and can be used to connect to a wide range of Linux servers, network switches, and routers. In short which devices your SSH to connect to paramiko is your best friend. It is a popular choice for network administrators and system engineers who need to automate tasks or access remote devices in a secure manner. Even If you are using Ansible without paramiko ansible is also useless because Ansible also uses the Paramiko library to connect to remote servers.

Python Script to SSH and Run Command

Python Script To SSH and Run Multiple Commands in Linux from explinux

Make sure you have all libraries installed on the server or in your Linux system. First, let’s start with preparation.

Preparation

  • Install pip if not in your machine. Check as per your Linux distro

for example rpm base system

yum install python-pip 
or
yum install python3-pip

for Debian based system

apt install python-pip
or
apt install python3-pip

You can install it according to your distro

  • Install the python package, and make sure you have internet active on the server
# pip install paramiko

The above python library is enough to connect remote server by ssh but if you want to export results in excel install openpyxl optional package

# pip install openpyxl

To support this python library mostly the time we face issues with the lxml python library because by default it has an older version installed on Linux.

# pip install --upgrade lxml

Finally, we have installed 3 python library

# pip install paramiko
# pip install openpyxl
# pip install --upgrade lxml

Start Scripting

Create a file with any name with .py extension here we will take the server_health.py file.

# vi server_health.py

We are showing commands for the Linux vi editor you can use your IDE or any editor.

For writing in the vi editor press “i” and to save data press the “esc” key then write in the lower left corner “:wq” and press enter to save and exit.

Related article:- Vi editor cheatsheet

Import Python Modules

First import python modules which are required in the script

import paramiko
from paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException, NoValidConnectionsError
import openpyxl
from os import path,rename

Now first we will write the script in a simple form then we will add a function to use multiple times.

Script Part

host = 'server1'
user = 'MyUserName'
password = 'MySecreteComplexPassword'
cmd = 'systemctl status sshd'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, password=password)
cmd=cmd
stdin, stdout, stderr = ssh.exec_command(cmd)
print(stdout.read())
print(stderr.read())
ssh.close()

Above script, we have defined 4 variables for the server host or hostname or IP, the user who is able to log in to the server, the password for the user, and cmd or command which we want to run on the remote server.

In the above script, we can see two outputs stdout which is the output of a successful command run, and stderr which is the output of an error in command. We are reading the output and printing them.

How to Run Multiple SSH Command On Remote Linux Machine

Our target is to run multiple commands on a Linux server for this we need to run through the python loop and we need a list of commands. Below is the script for a run multiple commands.

First, we need to convert our script to function and we need cmd list too

def getdata(host,user,password,cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, username=user, password=password)
    cmd=cmd
    stdin, stdout, stderr = ssh.exec_command(cmd)
    #stdout=stdout.read().splitlines()
    ot = stdout.read()
    oterr = stderr.read()
    print("--stdout--")
    print(ot)
    print("--stderr--")
    print(oterr)
    print(type(ot))
    ssh.close()

We have converted a python simple script to a function to use in a python for loop with the list of multiple commands.

# variables 
host = 'server1'
user = 'MyUserName'
password = 'MySecreteComplexPassword'
command = ['systemctl status sshd','systemctl status rsyslog']

# get data from remote host
def getdata(host,user,password,cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, username=user, password=password)
    cmd=cmd
    stdin, stdout, stderr = ssh.exec_command(cmd)
    #stdout=stdout.read().splitlines()
    ot = stdout.read()
    oterr = stderr.read()
    print("--stdout--")
    print(ot)
    print("--stderr--")
    print(oterr)
    print(type(ot))
    ssh.close()
 
# for loop with command list 
def cmdlist(command,host,user,password):
    if len(command) != 0:
        for cmd in command:
            getdata(host,user,password,cmd)
    else:
        print("Command length is 0 -ZERO. Please input atlease 1 command")

cmdlist(command,host,user,password)

Above script, we have changed the cmd variable to command and created a list of commands. And created a for loop with the list of commands and every time we loop we run the get data command which gives the output on each command. We are checking if the length of the command is zero then it will show us a warning for we need to input the command.

Here one question can rise why did not we use && or; to run commands in the same function, reason for that is in the loop data handling will be more complex if you run the command in that manner. But if you want to execute only and output data is not important then you can use && or “;”. For that case, you can add a command variable as below

cmd = 'systemctl status sshd rsyslog; nproc;free -m'

How to Run Multiple SSH Command On Multiple Remote Linux Machines

Now we will run multiple commands in multiple Linux machines for that we need to make our server variable into a list of variables and create a python for loop with the list of hosts or servers or machines.

# variables 
host = ['server1','server2','server3']
user = 'MyUserName'
password = 'MySecreteComplexPassword'
command = ['systemctl status sshd','systemctl status rsyslog']

# get data from remote host
def getdata(host,user,password,cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, username=user, password=password)
    cmd=cmd
    stdin, stdout, stderr = ssh.exec_command(cmd)
    #stdout=stdout.read().splitlines()
    ot = stdout.read()
    oterr = stderr.read()
    print("--stdout--")
    print(ot)
    print("--stderr--")
    print(oterr)
    print(type(ot))
    ssh.close()

# for loop with command list and server list
def cmdlist(command,host,user,password):
    if len(command) != 0:
        for h in host:
            for cmd in command:
                getdata(h,user,password,cmd)
    else:
        print("Command length is 0 -ZERO. Please input atlease 1 command")

cmdlist(command,host,user,password)

In the above script, we have converted the variable host to a list of hosts. and created a loop for the host list. This will go to all hosts and for each host all command run and get us the output.

Export Paramiko Output to an Excel File

As we all know you can not skip Excel or spreadsheet in any job so before someone ask for it export directly to excel with the help of a script. We use the python openpyxl library to export in excel.

def getandcreatewb():
    heading = ("hostname","command","output","Error")
    if path.exists("Health_Result.xlsx"):
        rename("Health_Result.xlsx","Health_Result_old.xlsx")
    workbook = openpyxl.Workbook()
    workbook.create_sheet("result")
    print(workbook.get_sheet_names())
    fsh=workbook.get_sheet_by_name('Sheet')
    workbook.remove_sheet(fsh)
    sheet = workbook["result"]
    sheet.append(heading)
    workbook.save("Health_Result.xlsx")

In the above script we are creating an excel file with the name Health_Result.xlsx if that file exists it renames it to Health_Result_old.xlsx. If you have more space you can rename it with DateTime and create a sheet name result and append a heading “hostname, command, output, Error”.

Here is a complete python script to ssh and run multiple commands in Linux and export in excel.

# variables 
host = ['server1','server2','server3']
user = 'MyUserName'
password = 'MySecreteComplexPassword'
command = ['systemctl status sshd','systemctl status rsyslog']

def getandcreatewb():
    heading = ("hostname","command","output","Error")
    if path.exists("Health_Result.xlsx"):
        rename("Health_Result.xlsx","Health_Result_old.xlsx")
    workbook = openpyxl.Workbook()
    workbook.create_sheet("result")
    print(workbook.get_sheet_names())
    fsh=workbook.get_sheet_by_name('Sheet')
    print(fsh)
    workbook.remove_sheet(fsh)
    sheet = workbook["result"]
    sheet.append(heading)
    workbook.save("Health_Result.xlsx")

# get data from remote host and append to excel workbook
def getdata(host,user,password,cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, username=user, password=password)
    cmd=cmd
    stdin, stdout, stderr = ssh.exec_command(cmd)
    ot = stdout.read()
    oterr = stderr.read()
    heading = ("hostname","command","output","Error")
    data = [(host,cmd,ot,oterr)]
    wb = openpyxl.load_workbook("Health_Result.xlsx")
    sheet = wb["result"]
    for d in data:
        sheet.append(d)
    wb.save("Health_Result.xlsx")
    ssh.close()


# for loop with command list and server list and create workbook
def cmdlist(command,host,user,password):
    if len(command) != 0:
        getandcreatewb()
        for h in host:
            for cmd in command:
                getdata(h,user,password,cmd)
    else:
        print("Command length is 0 -ZERO. Please input atlease 1 command")




cmdlist(command,host,user,password)

In the above script, we are calling create workbook function to our cmdlist loop function and appending our data in the paramiko get data function.

Conclusion

In this article, we have learned how to use paramiko to ssh and run multiple commands by the python script, and the best part we have exported it to excel. Next, we can use argparse to get input from the user and encrypt the password to use in the production environment.

Hope you find this article helpful, If yes share it with your friends.

]]>
Linux Directory Structure and 8 Important Directory Explained https://explinux.com/2023/01/linux-directory-structure.html Tue, 03 Jan 2023 19:55:10 +0000 https://explinux.online/?p=710 If you are looking for the Linux directory structure this is the right place for your search because here you will get answers for Linux directory structure and an explanation of important directories. You can use this article as a cheat sheet for the Linux directory structure.

Linux Directory Structure

Linux directory structure

The Linux directory structure is a tree-like hierarchy that is used to organize and store files on a Linux system. The root of the directory tree is represented by the forward slash (/), and all other directories and files are organized beneath it.

Here is a brief overview of some of the main directories that are commonly found in a Linux system:

  • bin: This directory contains essential binary executables that are needed to start the system and run basic commands.
  • /boot: This directory contains files that are needed to boot the system, including the Linux kernel, bootloader files, and system configuration files.
  • /dev: This directory contains device files that represent various devices that are connected to the system, such as printers, hard drives, and terminal devices.
  • /etc: This directory contains system-wide configuration files and scripts.
  • /home: This directory contains the home directories for all users of the system. Each user has their own subdirectory under /home, where they can store their personal files and configurations.
  • /lib: This directory contains libraries that are needed by programs in the /bin and /sbin directories.
  • /media: This directory is typically used to mount removable storage devices, such as USB drives or CD-ROMs.
  • /mnt: This directory is used to temporarily mount file systems, such as when performing system maintenance tasks.
  • /opt: This directory is used to store optional software packages that are not part of the default installation.
  • /proc: This directory is a virtual file system that contains information about the system’s processes and kernel.
  • /root: This is the home directory for the system’s root user.
  • /sbin: This directory contains system binary executables that are used for system maintenance and administration tasks.
  • /tmp: This directory is used to store temporary files that are created by programs.
  • /usr: This directory contains shared user data, such as libraries, documentation, and executables for programs that are installed on the system.
  • /var: This directory contains variable data, such as log files, spool directories, and temporary files that are created by system processes.

Related Article:-

22 Linux Commands

22 useful and productive commands

How to Install Python3.8 on Linux

RHEL 7 and some distro come with old python2.7, learn how to install python 3.8

Vi Editor Cheatsheet

Vi editor is the best editor in Linux check the cheat sheet to make your life easier

Brief Explanation for Important Directories

Below is an explanation of some important Linux directories below :

/etc Directory

The /etc directory in Linux is a system-wide configuration directory that contains configuration files and scripts that are used to control the operation of various system programs and services. It is a common location for storing global settings and preferences that apply to the entire system.

Some examples of the types of files that might be found in the /etc directory include:

  • System-wide configuration files for programs and services, such as the Apache web server or the SSH daemon
  • System-wide shell scripts that are run at boot time or when certain events occur, such as the rc scripts that are used to start and stop system services
  • System-wide security and authentication files, such as the passwd and shadow files that store user account information
  • System-wide environment variables and configuration files for the shell, such as bashrc
  • System-wide networking configuration files, such as hosts, resolv.conf, and network

The /etc directory is often used as a central location for storing system-wide configuration files because it makes it easy to find and manage all of the configuration files for the system in a single place. However, it is important to be careful when modifying the files in this directory, as changing the wrong settings can cause problems with the system’s operation.

/proc Directory

The /proc directory in Linux is a virtual file system that contains information about the system’s processes and kernel. It is a special kind of file system that does not exist on a physical storage device but is created dynamically by the kernel when the system is booted.

The /proc directory contains a number of files and directories that provide information about the state of the system and its processes. Some examples of the types of files and directories that might be found in /proc include:

  • /proc/cpuinfo: This file contains information about the system’s CPU, such as its model, speed, and number of cores.
  • /proc/meminfo: This file contains information about the system’s memory, such as the amount of free and used memory.
  • /proc/uptime: This file contains information about how long the system has been running since the last boot.
  • /proc/loadavg: This file contains information about the system’s load average, which is a measure of how busy the system is.
  • /proc/pid: This directory contains subdirectories for each running process on the system, with the name of each subdirectory corresponding to the process ID of the process. Each subdirectory contains a number of files that provide information about the process, such as its status, memory usage, and other details.

The /proc directory is a useful source of information about the system and its processes, and it can be accessed like any other directory on the system. However, it is important to note that the files in /proc are not stored on a physical storage device, and they may not always contain accurate or up-to-date information.

/bin Directory

The /bin directory in Linux is a directory that contains essential binary executables that are needed to start the system and run basic commands. These executables are used by both users and the system, and they include a wide range of tools and utilities that are necessary for the system to function.

Some examples of the types of executables that might be found in the /bin directory include:

  • Basic command line utilities, such as ls, cd, mv, and rm
  • System utilities, such as systemctl and init
  • Text processing utilities, such as grep, sed, and awk
  • Network utilities, such as ping and traceroute
  • File compression and decompression utilities, such as gzip and tar

The /bin directory is one of the directories that is included in the system’s PATH environment variable, which means that the executables it contains can be run from anywhere on the system simply by typing their names on the command line. This makes it convenient to use these tools and utilities without having to specify the full path to the executable file each time.

/sbin Directory

The /sbin directory in Linux is a directory that contains system binary executables that are used for system maintenance and administration tasks. These executables are typically used by system administrators and other users with special privileges, and they include a wide range of tools and utilities that are used to manage and maintain the system.

Some examples of the types of executables that might be found in the /sbin directory include:

  • System initialization and shutdown utilities, such as init and shutdown
  • System maintenance utilities, such as fsck and fdisk
  • Network configuration utilities, such as ifconfig and route
  • Disk management utilities, such as fdisk and mkfs
  • Hardware detection and configuration utilities, such as lspci and modprobe

The /sbin directory is typically not included in the system’s PATH environment variable, which means that the executables it contains must be run by specifying the full path to the executable file. This is done to prevent users without special privileges from running these executables by accident, as some of them can have serious consequences if used improperly.

/var Directory

The /var directory in Linux is a directory that contains variable data, such as log files, spool directories, and temporary files that are created by system processes. This directory is used to store data that is likely to change during the normal operation of the system, as opposed to the more static data that is stored in other parts of the file system.

Some examples of the types of files and directories that might be found in the /var directory include:

  • Log files, such as system logs, application logs, and web server logs
  • Spool directories, such as the /var/spool/cron directory, which is used to store cron job files
  • Temporary files, such as those created by the system’s package manager or by certain applications
  • Cache directories, such as the /var/cache/apt directory, which is used to store package cache files for the APT package manager
  • Lock files, which are used to prevent multiple processes from accessing the same resource at the same time

The /var/log subdirectory is a particularly important part of the /var directory, as it is used to store log files that can be used to troubleshoot problems with the system. It is a good practice to periodically review the log files in this directory to look for any issues or errors that might need to be addressed.

/lib Directory

The /lib directory in Linux is a directory that contains libraries that are needed by programs in the /bin and /sbin directories. A library is a collection of code that can be used by multiple programs to perform a common set of tasks. By storing libraries in a central location, such as the /lib directory, it is possible to reduce duplication of code and improve the efficiency of the system.

The /lib directory typically contains a variety of libraries, including shared object libraries (files with a .so suffix), static libraries (files with a .a suffix), and kernel modules (files with a .ko suffix). Some examples of the types of libraries that might be found in the /lib directory include:

  • System libraries, such as those that provide basic system functions, such as memory allocation and input/output operations
  • Libraries for programming languages, such as the C standard library or the Python standard library
  • Libraries for specific applications or services, such as libraries for the Apache web server or the MySQL database server

The /lib directory is an important part of the system’s file hierarchy, as it contains libraries that are needed by many of the programs and utilities that are used on the system. It is important to be careful when modifying the files in this directory, as changing the wrong library files can cause problems with the system’s operation.

/boot Directory

The /boot directory in Linux is a directory that contains files that are needed to boot the system, including the Linux kernel, bootloader files, and system configuration files. The /boot directory is typically one of the first directories that is accessed when the system starts up, as it contains the files that are required to load the kernel and start the system.

Some examples of the types of files that might be found in the /boot directory include:

  • The Linux kernel, which is the core of the operating system and is responsible for managing the system’s hardware and software resources
  • Bootloader files, such as the GRUB bootloader configuration file and the bootloader stage1 and stage2 files
  • System configuration files, such as the initrd file, which is used to load initial RAM disk images, and the system.map file, which contains a mapping of kernel symbols to addresses
  • Kernel modules are pieces of code that can be loaded into the kernel at runtime to add support for specific hardware devices or features

The /boot directory is an important part of the system’s file hierarchy, as it contains the files that are required to boot the system. It is important to be careful when modifying the files in this directory, as changing the wrong boot files can prevent the system from starting up correctly.

/tmp Directory

The /tmp directory in Linux is a directory that is used to store temporary files that are created by programs. These files are usually used to store data that is needed temporarily during the execution of a program, and they are typically deleted by the system or the program when they are no longer needed.

The /tmp directory is a good place to store temporary files because it is typically located on a file system that is specifically designated for temporary storage, such as a ramdisk or a partition with a relatively small amount of storage. This can help to improve the performance of the system by reducing the amount of disk I/O that is required to access the temporary files.

Some examples of the types of temporary files that might be stored in the /tmp directory include:

  • Temporary files that are created by applications, such as text editors or image editors
  • Temporary files that are created by the system, such as lock files or pid files
  • Temporary files that are created by shell scripts or other scripts that are run on the system

The /tmp directory is a good place to store temporary files because it is usually writable by all users on the system, which makes it easy for programs to create and access temporary files. It is important to note that the files in the /tmp directory are not permanently stored, and they may be deleted by the system or by other programs at any time.

Suggestion

Here are a few suggestions if you are a beginner for ways you can continue learning about Linux and its directories:

  • Explore the different directories on your Linux system and see what types of files and directories are stored in each one. You can use the ls command to list the contents of a directory, and the man command to learn more about the various utilities and commands that are available on the system.
  • Learn how to navigate the Linux file system using the command line. You can use commands like cd, pwd, and ls to move around the file system, and use wildcards and shell patterns to manipulate files and directories.
  • Practice using the find command to search for files and directories based on various criteria, such as their name, size, or modification time. This can be a useful skill for locating specific files or directories on the system.
  • Learn more about the various file system types that are supported by Linux, such as ext2, ext3, ext4, and XFS. Each file system has its own set of features and performance characteristics, and understanding these differences can help you choose the right file system for your needs.

Conclusion

Now we know about Linux directories structure and its usages and importance in Linux Operation systems. Hope this article works for you as a cheat sheet. Share this article with those who are learning and working on Linux.

]]>
AppArmor vs SELinux – Quick Comparison with Top 10 Advantages https://explinux.com/2023/01/apparmor-vs-selinux-quick-comparision.html Tue, 03 Jan 2023 11:51:33 +0000 https://explinux.online/?p=700 If you are looking for a comparison between AppArmor vs SELinux. This article will help you to choose which will fit your criteria. We have taken the top 10 reasons for your consideration between AppArmor vs SELinux.

AppArmor vs SELinux

AppArmor vs SELinux
AppArmor vs SELinux

SELinux

SELinux is a Linux security module that provides mandatory access control (MAC) and allows an administrator to specify fine-grained control over what processes are allowed to do on a system. It is mainly used to protect against malicious attacks and is implemented as a loadable kernel module. SELinux uses policies to define what actions are allowed in the system and supports a wide range of applications. It is mainly used on Red Hat-based systems. We have already covered this topic for more in-depth detail please read What is SELinux.

Related: How to disable SELinux?

AppArmor

AppArmor is a Linux security module that allows an administrator to specify fine-grained control over what programs are allowed to do on a system. It is a mandatory access control (MAC) system that uses profiles to specify what system resources an application is allowed to access. AppArmor is implemented in the Linux kernel and is thus more efficient than other MAC systems that are implemented as loadable kernel modules.

AppArmor is designed to protect against accidental system misconfigurations, rather than malicious attacks. It is mainly used on Debian-based systems and is relatively easy to configure and use compared to other MAC systems such as SELinux. AppArmor is also capable of protecting against certain types of security vulnerabilities, such as buffer overflows.

Top 10 Differences Between AppArmor vs SELinux

  1. AppArmor is a mandatory access control (MAC) system that was originally developed for Linux, while SELinux is another MAC system that was developed by the US National Security Agency (NSA).
  2. AppArmor uses profiles to specify what system resources an application is allowed to access, while SELinux uses policies to define what actions are allowed in the system.
  3. AppArmor is easier to configure and use than SELinux, but SELinux is more powerful and flexible.
  4. AppArmor provides protection at the file system level, while SELinux provides protection at the process level.
  5. AppArmor is implemented in the Linux kernel and is thus more efficient than SELinux, which is implemented as a loadable kernel module.
  6. AppArmor is mainly used on Debian-based systems, while SELinux is mainly used on Red Hat-based systems.
  7. AppArmor supports only a limited set of applications, while SELinux supports a wide range of applications.
  8. AppArmor is less secure than SELinux, as it is easier to bypass its security controls.
  9. AppArmor is mainly used to protect against accidental system misconfigurations, while SELinux is used to protect against malicious attacks.
  10. AppArmor and SELinux can be used together to provide enhanced security for a Linux system.

Top 10 Advantages of AppArmor over Selinux

  1. AppArmor is easier to configure and use than SELinux, making it more suitable for less experienced users.
  2. AppArmor uses profiles to specify what system resources an application is allowed to access, which can be more intuitive for users compared to SELinux’s policies.
  3. AppArmor is implemented in the Linux kernel, making it more efficient than SELinux, which is implemented as a loadable kernel module.
  4. AppArmor is mainly used on Debian-based systems, which are popular with many users.
  5. AppArmor supports a limited set of applications, which can make it easier to manage and maintain.
  6. AppArmor provides protection at the file system level, which can be sufficient for many users.
  7. AppArmor is less complex than SELinux and has a smaller codebase, making it easier to understand and troubleshoot.
  8. AppArmor is less prone to false positives (incorrectly blocking legitimate actions) than SELinux.
  9. AppArmor can be used in conjunction with other security measures, such as firewall rules, to provide enhanced protection for a system.
  10. AppArmor is more lightweight than SELinux and has lower overhead, making it suitable for use on systems with limited resources.

Top 10 Advantages of SELinux over AppArmor

  1. SELinux is a more powerful and flexible security system than AppArmor, as it provides protection at the process level rather than just the file system level.
  2. SELinux supports a wide range of applications, while AppArmor only supports a limited set.
  3. SELinux is more secure than AppArmor, as it is harder to bypass its security controls.
  4. SELinux is mainly used on Red Hat-based systems, which are popular with data centers and production environments.
  5. SELinux policies are more granular and allow for more fine-grained control over system actions compared to AppArmor profiles.
  6. SELinux can be configured to enforce different security policies for different users, groups, and processes, providing a higher level of security.
  7. SELinux can protect against both accidental system misconfigurations and malicious attacks, while AppArmor is mainly focused on protecting against accidental misconfigurations.
  8. SELinux can be used to enforce separation between different domains, such as separating the network and file access, providing an additional layer of security.
  9. SELinux is actively maintained and supported by the Linux community and the US National Security Agency (NSA).
  10. SELinux provides a system-wide security policy, rather than just protecting individual applications, making it more comprehensive in its coverage.

Which one is best between AppArmou vs SELinux

It is difficult to say which is “best” between SELinux and AppArmor, as it ultimately depends on your specific needs and goals. Please consider the below point to choose the best suit for you :

  • Purpose: SELinux is mainly used to protect against malicious attacks, while AppArmor is mainly used to protect against accidental system misconfigurations. If you are primarily concerned with protecting against malicious attacks, SELinux may be a better choice. If you are mainly concerned with protecting against accidental misconfigurations, AppArmor may be sufficient.
  • Ease of use: AppArmor is generally easier to configure and use than SELinux, so if you are less experienced with Linux security or do not want to spend a lot of time setting up and maintaining your security system, AppArmor may be a better choice.
  • Flexibility: SELinux is more flexible than AppArmor, as it provides protection at the process level and supports a wide range of applications. If you need more granular control over system actions or want to protect a wide range of applications, SELinux may be a better choice.
  • System resources: AppArmor is implemented in the Linux kernel and is more efficient than SELinux, which is implemented as a loadable kernel module. If you are running a system with limited resources, AppArmor may be a better choice.

Conclusion

This comparison of AppArmor vs SELinux will let you decide which one is best for your need. Ultimately, the decision will depend on your specific needs and goals. It is also possible to use both SELinux and AppArmor together to provide enhanced security for your system.

]]>
What is SELinux? 20 Advantages of SELinux https://explinux.com/2023/01/what-is-selinux.html Tue, 03 Jan 2023 10:33:39 +0000 https://explinux.online/?p=690 What is SELinux?
What is SELinux

SELinux (Security-Enhanced Linux) is a Linux kernel security module that provides a security mechanism for supporting access control policies. It was developed by the National Security Agency (NSA) as a way to enhance the security of Linux systems.

SELinux provides mandatory access controls (MAC) in addition to the traditional discretionary access controls (DAC) that are implemented in the Linux kernel. DAC controls are based on the permissions assigned to files and directories, and they allow the owner of a file or directory to determine who has access to it. MAC controls, on the other hand, are based on the security context of a process and allow the system administrator to define more fine-grained access controls.

SELinux was introduced as a way to address the limitations of DAC and provide an additional layer of security to Linux systems. It is especially useful in environments where security is a high priority, such as in government, military, or financial organizations.

While you can use Linux without SELinux, it is generally considered a good idea to use it if your system requires a high level of security. If you do not need the additional security provided by SELinux, you can disable it or run Linux in permissive mode, which allows SELinux to enforce policies but does not block any actions that would violate those policies.

Related Article:-

How to check and disable SELinux?

How to check and disable firewall in RHEL and CentOS?

Advantages of SELinux

Here are some benefits of using SELinux on your Linux systems:

  1. Enhanced security: SELinux provides an additional layer of security by enforcing mandatory access controls.
  2. Fine-grained control: SELinux allows you to define very specific access controls based on the security context of a process.
  3. Improved system integrity: SELinux can help prevent unauthorized changes to system files and configurations.
  4. Increased compliance: SELinux can help you meet regulatory requirements for security.
  5. Reduced vulnerabilities: SELinux can help reduce the risk of vulnerabilities in your system by restricting access to sensitive files and processes.
  6. Improved isolation: SELinux can help isolate different processes and prevent them from interfering with each other.
  7. Enhanced auditing: SELinux provides detailed logs of system activity, making it easier to audit and monitor your system.
  8. Improved system stability: SELinux can help prevent malicious or misbehaving processes from disrupting the system.
  9. Enhanced confidentiality: SELinux can help protect sensitive data from being accessed by unauthorized processes.
  10. Improved system availability: SELinux can help prevent denial of service attacks by limiting access to system resources.
  11. Enhanced resilience: SELinux can help prevent attackers from gaining a foothold on your system.
  12. Improved resource utilization: SELinux can help ensure that processes only have access to the resources they need, improving overall system performance.
  13. Enhanced separation of duties: SELinux can help enforce the separation of duties between different users and processes.
  14. Improved traceability: SELinux provides detailed logs of system activity, making it easier to trace the actions of processes.
  15. Enhanced system forensics: SELinux can provide valuable information for forensic investigations.
  16. Improved flexibility: SELinux can be customized to meet the specific security needs of your organization.
  17. Enhanced scalability: SELinux can be used on systems of any size, from small standalone systems to large enterprise environments.
  18. Improved interoperability: SELinux can be used with other security technologies to provide a comprehensive security solution.
  19. Enhanced reliability: SELinux can help prevent system failures and improve overall reliability.
  20. Improved usability: SELinux can be configured to allow users to perform their tasks while still enforcing strict security policies.

Alternatives of SELinux

SELinux is not alone that providing MAC-level security there are many other players in this category. Some alternative options to SELinux for implementing mandatory access controls on Linux systems include:

  • AppArmor: This is a security extension for the Linux kernel that allows you to specify access controls for programs. It is similar to SELinux in that it provides a way to enforce security policies, but it uses a different syntax and approach.
  • TOMOYO Linux: This is another security extension for the Linux kernel that provides MAC controls. It was developed in Japan and is used in a number of Linux distributions in Asia.
  • Grsecurity: This is a set of patches for the Linux kernel that includes a number of security features, including MAC controls. It is not a standalone security module like SELinux or AppArmor, but rather a collection of enhancements to the kernel.
  • Smack: This is a simple MAC system for Linux that is designed to be easy to use and understand. It is not as feature-rich as SELinux or AppArmor, but it can be a good choice for systems that do not require a high level of security.
  • GnuTLS: This is a library that provides support for secure communications, including support for X.509 certificates. It can be used as an alternative to SELinux for implementing secure communication channels on a Linux system.

There are many other security tools and frameworks available for Linux that can be used to enhance the security of your system.

Linux Distributions Provides SELinux

SELinux is not enabled by default on all of these distributions, but it is usually available as an option that can be enabled during installation or enabled later on. Some distributions, such as RHEL and CentOS, are designed with a focus on security and include SELinux as a key component of their security strategy. Other distributions may not prioritize security as highly but still offer SELinux as an optional security feature.

Conclusion

In this article, we get to know about what is SELinux and its advantages and alternatives. SELinus provides MAC-level security and if you need a security system then you must use it. We can consider other options al well. Hope you Like the article.

]]>