Linux Commands – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Fri, 12 Mar 2021 15:08:05 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 Wall Command in Linux with Examples https://linuxhint.com/wall-command-in-linux-with-examples/ Fri, 12 Mar 2021 12:03:14 +0000 https://linuxhint.com/?p=94100 In a Linux environment, there are scenarios when multiple users are working on the server simultaneously through SSH. However, sometimes system admin needs to restart or shut down the system due to e.g. system maintenance, kernel upgrade, adding or removing hardware from the server. If this is the case, the system admin should inform all logged-in users to save their work. Email does not fit in this situation, as you first have to find out who is logged in and then sending emails to them. Also, you do not know when the user will read the email. Luckily, there is a Linux command “wall” that allows you to do this easily.

Here, we are going to describe the usage of wall command in Linux. Remember, the wall command works the same for all Linux distributions.

Note: Wall command only displays the message on the Terminal window of logged-in users. Users working only on GUI, with no Terminal window open will not be able to see the messages.

Linux Wall Command

Linux Wall command allows you to send a message or the contents of a file to all the currently logged-in users. If no file or message is specified, wall command reads the message from the stdin (standard input).

Wall Command Syntax

The syntax for wall command is as follows:

$ wall [options] [message-or-filename]

Send a Message to All Users

To send a message to all the currently logged-in users, type wall followed by the message you want to send.

$ wall System is going down for 1-hour maintenance.

This command will send the message to all the logged-in users with a Terminal window open.

Note: For some Linux distributions, you have to execute the above command as super user. Also, if a user has chosen to deny messages to their Terminals (like using the mesg command), then only a sudo user will be able to send messages to their Terminals.

Following are the outputs displayed to two users “linuxways” and “ummara” who are logged-in to the server via SSH. These users are working from the system running Ubuntu and Debian.


The wall command also reads the message from stdin (standard input). To do so, simply type wall and hit Enter.

$ wall

After that, type any message or messages you want to send to logged-in users. Once you are done typing the messages, press Ctrl+D to send those messages.

this is first line

this is second line

.

Here is the output which all logged-in users received on their Terminal.

Send a Message from a File

If there are some messages that you have to repeat often, you can simply type them in a file. When you have to send those messages to the logged-in users, simply call that file with wall command. Remember, you will require sudo privileges if you want to send a message from a file.

$ sudo wall <filename>

For example in the following output, file content has been first shown using the cat command. Then to send the message contained in the file, the filename is passed to the wall command.

These are the outputs (from the file msg.txt) received by the logged-in users.

Send a Message to a Group

Instead of sending the message to all logged-in users, you can send it to only the members of a group who are currently logged in to your system. The syntax is as follows:

$ wall -g [group] [message]

For example, to send a message to a group named “sshusers”, the command would be:

$ wall -g sshusers System is going down for 1 hour maintenance.

All the members of the “sshusers” group who are currently logged in to the server will receive the specified message.

Suppress Banner

The wall command displays a banner before displaying a message as can be seen in the following screenshot.

To suppress this banner, use the -n option with the wall command:

$ wall -n <message>

For example, the following command will only display the specified message while suppressing the banner.

$ wall -n System is going down for 1 hour maintenance.

All the logged-in Terminal users will receive the message without a banner.

View Version Information

To view the version of the wall command, use the following command:

$ wall -V

The following output shows the version of the wall utility is 2.34.

Wall is a handy utility that helps a multi-user system admin to quickly notify other users to save their work before a system shutdown or reboots. In this article, we covered how to use the wall command to communicate with logged-in users. Hope you find it interesting and useful.

]]>
How to Fix “failed to start hostname.service unit hostname.service is masked” Error https://linuxhint.com/fix-failed-to-start-hostname-service-error/ Tue, 09 Mar 2021 05:23:33 +0000 https://linuxhint.com/?p=93550 Whenever you bring in a new computer system, there is a default hostname associated with it that is mapped onto a specific IP address. However, you can always change this hostname for your convenience. Once you change the hostname of your Linux-based system, you should always restart the “hostname.service” module for the new changes to take effect. Sometimes, when restarting this service, you may encounter the “failed to start hostname.service unit hostname.service is masked” error. This article highlights the root cause of this error and shows you how to resolve this error.

Causes of the Error

The system hostname is stored in two main files in Linux. The first file is the “/etc/hostname” file, and the other file is the “/etc/hosts” file. The former only consists of the hostname of your system, whereas the latter contains a mapping of the hostname onto a specific IP address. The “failed to start hostname.service unit hostname.service is masked” error arises when the contents of these two files are mismatched, i.e., the hostname mentioned in one of these files is different from the hostname in the other file. Due to this inconsistency between the contents of the “/etc/hostname” and “/etc/hosts” files, your system will fail to start the hostname.service, and the error will occur.

How to Resolve the Error

The simplest way to resolve this error in Linux is by ensuring that the hostname mentioned in both files is the same. To do so, you will need to check the contents of both these files. You can access the “/etc/hostname” file by executing the following command in the Linux terminal:

$ sudo nano /etc/hostname

Our “/etc/hostname” file is shown in the image below:

The “/etc/hosts” file can be accessed with the following command:

$ sudo nano /etc/hosts

Our “/etc/hosts” file is shown in the image below:

As you can see from the contents of both files, our hostname is the same in both files, i.e., kbuzdar-VirtualBox. Once you have ensured that the hostname in your respective files is exactly the same, then you can try restarting the hostname.service once again. This time, it should not render the error.

Conclusion

This article enlightened you about the causes of the “failed to start hostname.service unit hostname.service is masked” error. Moreover, it also shared with you the simplest method through which you can get rid of this error in Linux.

]]>
Chattr command in Linux https://linuxhint.com/chattr-command-linux/ Tue, 09 Mar 2021 02:54:28 +0000 https://linuxhint.com/?p=93171 If various users are using your Linux system, these users can mess with an important common set of files. As an administrator of the device, you would not want some files to be deleted or modified unintentionally. In such cases, “chattr,” also called the “Change Attribute” command, is used, which is designed to confront these kinds of situations.

In Linux, every file has some metadata properties, which include attributes and these attributes can be set or cleared, and few attributes can only be viewed. This command’s primary objective is to make important files secure and prevent them from being deleted accidentally.

Firstly, let’s check the syntax of “chattr” command:

chattr [operator] [flag] [filename]

The operators are:

Operators Description
+ To add the attribute to a file
To remove the attribute from a file
= Keep the selected attributes to be the only attribute that files have

Now let’s check the list of flags that are used with the “chattr” command:

Flag Description
A When set, a time (access time) record remains unchanged
S When set, the changes are updated synchronously on the disk
a When set, the file opens in append mode to write
i When set, the file becomes unmodifiable, and only the superuser can enable it
j When set, all information is updated on the ext3 journal before the file itself
t When set, no tail merging
u When set for a file, its data is saved. This enables the user to undelete the file
e This attribute indicates that the file is using the extents to map block on memory

Let’s further understand the “chattr” with examples:

How to add read-only restriction to a file using the “chattr” command:

Firstly, the most common use of the “chattr” command sets the immutable flag “i”. Let’s create a file by the name “myfile.txt” and make it read-only using the command:

$sudo chattr +i myfile.txt

A lock icon will appear on the file after applying the “i” flag, as shown in the above image. After setting the flag, the file will no more be editable, as shown in the following image:

Multiple flags can also be set; for example, if you want to make a file read-only and restrict access record as well, then use:

$sudo chattr +iA myfile.txt

How to remove the read-only restriction to a file using the “chattr” command:

If you want to remove these setting the use the command given below:

$sudo chattr -i myfile.txt

As it can be viewed, that the file can now be modified after eliminating the “i” flag.

How to give append-only access to a file using the “chattr” command:

To give append-only permission to a file, an “a” flag can be set. The objective of “a” flag is to permit users to add something to a file and restrict to change data that is already in the file:

$sudo chattr +a myfile.txt

Let’s check it with an example:

As shown in the above images, the text can only be appended, but it cannot overwrite the existing text.

Similarly, to remove the access use:

$sudo chattr -a myfile.txt

After removing the restriction, the file can be overwritten, as depicted in the above images.

How to set the restriction to a directory using the “chattr” command:

A whole directly can also be restricted using the “chattr” command. For this guide, I have created a directory by the name of “mydir” with some files in it:

$ sudo chattr –R +i ./mydir/

To verify it, try to remove a file:

As it can be seen, the operation is not permitted.

How to check applied “chattr” attributes to a file:

To check which attributes have been set, use the command shown below:

$lsattr myfile.txt

Conclusion:

Change attribute is the handy command-line tool to modify file permissions. It helps protect the important files and prevent them from being altered if your system uses multiple users. In this guide, we discussed how to use the “chattr” command to modify metadata properties to change the permission of the file using different flags. ]]> HardInfo: Check Hardware Information in Linux https://linuxhint.com/hardinfo-check-hardware-information-linux/ Mon, 08 Mar 2021 10:05:13 +0000 https://linuxhint.com/?p=93445 Computer hardware is a combination of various components, such as motherboard, CPU, GPU, memory, and other I/O devices. It is good for Linux users to have a basic knowledge of the hardware components of the system that they are currently using. This will help administrators to manage the required devices accordingly.

This article shows you how to check the hardware information in Ubuntu using various methods. These options are discussed in the sections that follow.

Checking Hardware Information Using HardInfo

To get hardware information using HardInfo, you first need to install HardInfo on your Linux system. Start the installation process by opening the terminal and running the following command:

$ sudo apt-get install hardinfo

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image1 final.png

After installing HardInfo on your system, open the utility via the command-line to see the hardware information in the GUI. To open HardInfo, simply enter the following command:

$ hardinfo

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image3 final.png

A new window will open after you run this command. If you click on “Summary,” you will get all system-related information, including the processor, OS, display, etc.

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image2 final.png

To check the status of the Operating System, including the version, PC name, distribution, etc., go to the “Operating System” window. A screen will appear with detailed information, as shown in the image below:

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image5 final.png

To check the system’s kernel version, select the “Boot” window. This window will show you the updated version information with the date and time.

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image4 final.png

To get package information, click “Processor.”

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image7 final.png

Clicking “Memory” will display the memory status, including the total memory, available memory, used memory, cache, active, inactive status, etc.

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image6 final.png

Select “Input Devices” to get more icons to view specific system details. Click a specific icon to reveal relevant details related to that icon.

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image9 final.png

To obtain details about the system network, click the “Network” option:

So, this is how you can find hardware system details using HardInfo.

If you prefer to check the hardware information via the command-line, then follow the steps mentioned below.

Checking Hardware Information Using the Command-Line

This section covers some important commands that can be used to fetch hardware information via the terminal. The ishw command is used for this purpose.

System Hardware Information

The “lshw” utility helps users to print system information such as hardware components, which can include Cpu, disks, cache, etc. Though this utility is built-in, but if your system does not have this utility, then you can install it using the following command:

$ sudo apt-get install lshw

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image12 final.png

Now, to print the hardware information, use the following command:

$ sudo lshw

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image10 final.png

The output of this command includes every minor detail related to the system. To get a summary of this information, use the “short” command. The information will be printed in a table organized into columns:

$ sudo lshw –short

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image11 final.png

CPU Information

The “lscpu” command will fetch CPU details from the “sysfs” files.

To display cpu information, use the following command:

$ lscpu

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image13 final.png

Block Device Information

The “lsblk” command is used to collect block device, storage, and other information related to the hard disk, flash drive, etc.

To list data using this command, issue the following in the terminal:

$ lsblk

The output will provide a list of information on the screen. To check all block devices, issue the following:

$ lsblk -a

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image14 final.png

USB Controller Information

To view information about the devices that are connected to the system, including USB controllers, enter the following command:

$ lsusb

D:\Kamran\Feb\16\Warda\Linux Hardware Info\images\image15 final.png

Conclusion

This article provided a brief introduction to getting Linux system hardware information using the HardInfo utility. We have also displayed all the necessary commands for readers who want to check this through the command-line.

]]>
Linux List All IP Addresses on the Interface https://linuxhint.com/list-ip-addresses-interface-linux/ Fri, 26 Feb 2021 18:07:41 +0000 https://linuxhint.com/?p=91808

All the people who belong to the networking background know that an IP address acts as a unique identifier of the devices within a network. Therefore, we must know the IP addresses of the devices within a network to enable smooth network communication. Today’s article will focus on the different methods of listing all the IP addresses on the Interface in Linux Mint 20.

Methods of listing all IP Addresses on the Interface in Linux Mint 20

For listing all the IP addresses on the Interface in Linux Mint 20, you can pick any of the following four methods.

Method # 1: Display all Network Interfaces and their IP Addresses

You can display all the network interfaces and their respective IP addresses in Linux Mint 20 by executing the built-in Command shown below:

$ ip addr show

The results from the execution of this command are shown in the following image:

Method # 2: Display all the IPv4 Addresses

If you want to display all the IPv4 addresses on the Interface only in Linux Mint 20, then you can execute the command shown below:

$ ip -4 addr

All the IPv4 addresses are shown in the following image:

Method # 3: Display all the IPv6 Addresses

If you want to display all the IPv6 addresses on the Interface only in Linux Mint 20, then you need to execute the Command shown below:

$ ip -6 addr

All the IPv6 addresses are shown in the following image:

Method # 4: Display all the IP Addresses in the Connected Network

You can also display all the IP addresses in the connected network in Linux Mint 20 by following the procedure described below:

Step # 1: Install the “arp-scan” Command in Linux Mint 20

First, you need to install the “arp-scan” Command in Linux Mint 20, which will later be used to list all the IP addresses in the connected network. This is not a built-in command in Linux, but it can be installed by executing the following Command:

$ sudo apt-get install arp-scan

Once this Command is installed on your Linux Mint 20 system, you will be able to use it for listing down all the IP addresses in the connected network.

Step # 2: Find your Network Interface Name with the “ifconfig” Command in Linux Mint 20

Before using the “arp-scan” Command, you need to find your network interface name with the command shown below:

$ ifconfig

In our case, the network interface name is “enp0s3” as shown in the following image. This network interface name will be used with the “arp-scan” Command in the next step.

Step # 3: Use the “arp-scan” Command for displaying all the IP Addresses in the Connected Network in Linux Mint 20

Now, you can use the “arp-scan” Command for displaying all the IP addresses in the connected network in Linux Mint 20 in the manner shown below:

$ sudo arp-scan --interface=NetworkInterfaceName --localnet

Here, it would be best if you replaced NetworkInterfaceName with the name of your particular network interface. In our case, it was “enp0s3” that we found out in step # 2.

The results from the execution of this Command are shown in the following image:

Conclusion

By picking any method (according to your requirements) from the ones that have been presented to you in this article, you can easily list all the IP addresses on the Interface in Linux. All of these methods have been performed on Linux Mint 20 for testing. However, the very same methods can also be employed on Debian 10 and Ubuntu 20.04.

]]>
How Can I Sudo Another User Without A Password? https://linuxhint.com/sudo-another-user-without-a-password/ Mon, 22 Feb 2021 15:27:40 +0000 https://linuxhint.com/?p=90937

In Linux platforms, a sudo user is a tool that implies “superuser do” to run various systems’ commands. A sudo user is typically a root user or any other user who has some privileges. To delegate important tasks like server rebooting or restarting the Apache server, or even to create a backup using the sudo command, you can use the sudo without having to enter the password again and again.

By default, sudo user needs to provide some user authentication. At times, user requirements are to run a command with these root privileges, but they do not desire to type a password multiple times, especially while scripting. This is easily doable in Linux systems. In this article, we will check the method to sudo another user without entering their password.

Running sudo command without a password

To back up your sudo users, you need to copy the /etc/sudoers file from one place to another. Use the following command to do so:

$ sudo cp /etc/sudoers /root/sudoers.bak

Now, to edit the /etc/sudoers file, we will be using the visudo command. This will open up the sudoers file.

$ sudo visudo

To edit the /etc/sudoers file, users need to rectify the entries as per your need. Adding another user to sudo will allow users to execute any command without any password. In the file above, append the following command.

UserName ALL = NOPASSWD: /bin/systemctl restart httpd.service, /bin/kill

Replace the UserName with the name of the user you want to set in the file.

Then, save and exit the file using the Ctl+O shortcut.

Execute ALL sudo commands without a password

For adding a group to sudo without providing a password, use the % character before the name of your group. But first, open up the visudo editor, using the command below:

$ sudo visudo

Once you have opened up the editor window, you need to add the following line in order to add the group and to run all of the commands without a password.

%group ALL=(ALL) NOPASSWD: ALL

Here, replace the group name with the group you want to adjust the settings for.

Allowing a user to run /bin/kill

To allow a user to run the /bin/kill command using the sudo privileges without providing a password, append the following line in the same editor window:

UserName ALL=(ALL) NOPASSWD: /bin/kill

Replace the UserName with the name of the user you want to adjust the settings for.

In the same way, to enable the members of a group to run the sudo commands /bin/kill, /bin/rm without the need of entering any password, run the appended command:

%group ALL=(ALL) NOPASSWD: /bin/kill, /bill/rm

Testing the changes

To test the changes, you can now run the /bin/kill command, which will be used to kill any process whose ID is provided. This time you will not be needing a password:

$ sudo /bin/kill PID

Conclusion

In this article, we saw the method to run any command without providing the password while using sudo on different Linux platforms. Though it is considered to be risky for security purposes,  password-less operations are risky and are an extra feature for secure systems.

]]>
How to Use the “find” command in Linux to Search Files? https://linuxhint.com/use-the-find-command-in-linux-to-search-files/ Wed, 17 Feb 2021 10:52:43 +0000 https://linuxhint.com/?p=90049 If you are a Linux user, then you can’t just rely on GUI to perform various tasks, therefore, a solid grasp of terminal commands is really essential. All distributions based on Linux run the commands to perform different administrative tasks.

Although the Linux terminal is a text interface that seems complex, it is actually very flexible, easy to use, and quite a useful tool. Commands can easily be copied from online sources and pasted into the terminal to perform various operations. There are tons of commands but this post will focus on the “find” command.

The “find” command is used to find, filter, or search files and folders in your system according to user-specified conditions and perform several operations on them.

Let’s discuss how to use the “find” command, its syntax, and various operations performed by this command in detail.

Syntax of “find” Command in Linux

The “find” command syntax is shown below:

find [path] [options] [expression]

Three attributes go with the “find” command:

  • [path]: It defines the directory where to begin searching.
  • [options]: It defines the criteria of filtering e.g. searching a file/folder by its name, permission, time, or date.
  • [expression]: It defines what actions to perform with the file.

All of the above attributes are optional as they can be used according to the requirement.

For demonstration, I have created different directories and some text files, see the image below:

find/1%20copy.png

Finding a File by Name

To search the file by name, use the below-given command:

$ find . -name MyTextFile1.txt

find/2%20copy.png

The dot after “find” in the above command indicates the current directory.

If you don’t remember the exact file name, the search can further be refined and make it case-insensitive by using the “-iname” in the place of “name”:

$ find . -iname mytextfile1.txt

find/3%20copy.png

Finding a File by Type

To find a file by its type, use the “-type” option with letters that are also known as descriptors such as “f” for files, “d” for directories, “l” for the symbolic link, and “s” for sockets.

To search all directories use:

$ find . -type d

find/4%20copy.png

To search for files, use:

$ find . -type f

c%20copy.png

Finding a File by the File Extension

To search the file by pattern, e.g., file extension, such as displaying all the files with “.txt”, use the following command:

$ find . -name *.txt

find/5%20copy.png

All the files with “.txt” will be displayed along with their corresponding directories.

Finding and Deleting a File

To search and delete a file, use the command below:

$ find . -iname mytextfile1.txt -exec rm {} \;

find/6%20copy.png

The above command first searches the file and then delete it. The image is demonstrating that “MyTextFile1” has been deleted.

To delete all files with extension “.txt”, you can use the appended command:

$ find . -name *.txt -delete

find/7%20copy.png

Finding a File by Size

The “find” command can also search a file by size. Simply use “-size” option along with its descriptors such as “b” for 512 Kb blocks, “c” for bytes, “k” for kilobytes, “M” and “G” for megabytes and gigabytes respectively:

$ find . -type f -size -1024c

find/8%20copy.png

The command mentioned above searches all files with a size less than 1024 bytes. The search can further be refined, for instance, if we want to find all the files that are less than 1Mb, then we use the command below:

$ find . -type f -size 1M

ab/a%20copy.png

For all the files that are greater than 1Mb, use the command below:

$ find . -type f -size +1M

ab/b%20copy.png

A range of size can also be defined, using the appended command:

$ find . –type f -size +1M -size 10M

Finding Files by Permission

To search a file by permission, we will use the “-perm” option, then permission code, as demonstrated below:

$ find . -perm 664

find/10%20copy.png

Find a Text Within Text Files

To find text in multiple text files in your system,s use the command given below:

$ find . -type f -name *.txt -exec grep ‘Hello’ {} \;

find/12%20copy.png

The command is searching the “Hello” word in the text files. The output is text strings from the text files containing “Hello”.

Finding a File by Modification Date and Time

To access a file by its last modification, use the command below:

$find . -type f -iname *.txt -mmin +10

find/13%20copy.png

The above command is searching for a file last modified four minutes ago, and “m” signifies the “Modification”.

$find . –type f -iname *.txt -amin -10

find/14%20copy.png

The above command is searching for a file last accessed 4 mins ago, and the “a” in “amin” is signifying “Access”. To access a file that wasmodifiedfour days ago, use “-mtime +4” in the place of “mmin +4”.

Conclusion

The “find” command in Linux is a very useful command that lets you search a file or directory using different criteria, and even allows you to modify the files from the terminal. In this guide, we observed the syntax of the “find” command in Linux and learned how to use the “find” command to perform various functions.

]]>
Linux “getopts” Example https://linuxhint.com/getopts-usage-example-linux/ Tue, 05 Jan 2021 08:13:15 +0000 https://linuxhint.com/?p=84443 “getopts” is a very useful command in Linux that is mostly incorporated within bash scripts to take flags and arguments as inputs from the user. To further elaborate on the usage of this command in Linux Mint 20, we will be sharing with you two different examples of its usage in this article.

“getopts” Examples in Linux Mint 20:

For an easier and a better understanding of the “getopts” command in Linux Mint 20, we have designed for you two example scenarios. Before heading on to these scenarios, you can check out the help manual of the “getopts” command in Linux Mint 20 terminal so that you may get the basic idea about the syntax of this command. You can see the help manual of this command by executing the “help” command:

$ getopts --help

The help manual of the “getopts” command, will contain a brief description of the usage of this command along with its syntax as shown in the image below:

Now when we have gone through the help manual of the “getopts” command, we can proceed with our example scenarios as follows:

Case # 1: Passing Flags to a Bash Script for its Execution in Linux Mint 20:

In this example, we will be creating a bash script that will take a flag as input from the user along with the execution command of that bash script. Depending upon the value of the provided flag, the respective output will be displayed. The detailed description of the steps involved in this scenario is as follows:

Step # 1: Writing a Bash Script:

First, we will write a bash script in our Home directory. We have named this file as getopts.sh. The contents of this bash script are shown in the image below. In the bash script shown below, we have a “while” loop that runs on the “getopts” command. Here, this “getopts” command is used to take a flag as input from the user. The value of this flag can either be “r”, “y”, or “g” representing the “red”, “yellow”, and “green” colors respectively. The “option” variable will be used to store the value of the flag provided by the user. Then we have used a “case” statement on the value of the provided flag which will display a customized message depending upon the value of the “option” flag. Finally, we have closed the “case” block with the “esac” statement and the “do” block with the “done” statement.

Step # 2: Testing the Bash Script:

After creating and saving our bash script, now it is time to run it. We will be testing all the cases one by one. First, we will run the bash script with the “-r” flag to see if it produces the correct output or not in the following manner:

$ bash getopts.sh –r

The customized output of our bash script with the “-r” flag is shown in the image below:

Now, we will run the bash script with the “-y” flag to see if it produces the correct output or not in the following manner:

$ bash getopts.sh –y

The customized output of our bash script with the “-y” flag is shown in the image below:

Now, we will run the bash script with the “-g” flag to see if it produces the correct output or not in the following manner:

$ bash getopts.sh –g

The customized output of our bash script with the “-g” flag is shown in the image below:

Finally, we will run our bash script with any random flag, i.e. a flag that is not valid or a flag that is not mentioned in our bash script says “-a” in the following manner:

$ bash getopts.sh –a

This time, the default case of our bash script has been executed which has displayed an error message since we have used an invalid flag.

Case # 2: Passing Flags along with Arguments to a Bash Script for its Execution in Linux Mint 20:

In this example, we will be creating a bash script that will take a flag and an argument as input from the user along with the execution command of that bash script. Depending upon the value of the provided flag and argument, the respective output will be produced. The detailed description of the steps involved in this scenario is as follows:

Step # 1: Writing a Bash Script:

The bash script used for this case is shown in the image below and is very much similar to the one we created for our case # 1. The only difference is that this time, we are not allowing multiple flags. The user is only allowed to enter the “-r” flag. However, the “:” colon after the “r” flag in the bash script indicates that the user is also supposed to provide an argument along with the flag. This argument will be stored in the default “OPTARG” variable. For displaying the value of the provided argument with the “echo” command, we have used a “$” symbol before the “OPTARG” variable.

Step # 2: Testing the Bash Script:

After saving this bash script, now is the time to test it. Again, we will be testing all the cases one by one. First, we will run the bash script with the “-r” flag and a sample argument “black” to see if it produces the correct output or not in the following manner:

$ bash getopts.sh –r black

The customized output of our bash script with the “-r” flag and “black” argument is shown in the image below:

Now, we will test this script with an invalid flag and a valid argument in the following manner:

$ bash getopts.sh –a black

This time, the default case of our bash script has been executed which has displayed an error message since we have used an invalid flag.

Now, we will run this bash script while omitting the flag and just passing a valid argument in the following manner:

$ bash getopts.sh black

This time, no output will be produced on the terminal or in other words, our bash script will not execute since we have skipped a mandatory flag.

Finally, we will run this bash script while omitting the argument and just passing the valid flag in the following manner:

$ bash getopts.sh –r

Again this time, the default case of our bash script has been executed which has displayed an error message since we have skipped the mandatory argument.

Conclusion:

These two examples are a very nice depiction of the usage of the “getopts” command in a bash script in Linux Mint 20. You can even create more complex scenarios in bash and pair them up with the “getopts” command to take more than one argument and flags from the user as inputs.

]]>
Linux Chmod Command Tutorial for Beginners https://linuxhint.com/linux_chmod_command_tutorial_beginners/ Mon, 04 Jan 2021 20:26:17 +0000 https://linuxhint.com/?p=84173

Most of the fresh users to Linux are searching for a way via the command prompt to modify the file/directory permissions. Those users would be pleased to know that there is a command – dubbed or chmod, e.g. change mode – that help you do this quickly. Chmod modifies each document’s rights by mode, in which the mode specifies the privileges to be updated. You may designate a mode with octal numerical or letters.

Understand the Mode Privileges

To understand the chmod, you have first to understand simple things regarding it. Open the command terminal and list all the directories or folders to check the privileges assigned to owners, groups, and others. You have to use the list command followed by the –og keyword. It will display the folder type, e.g. d belongs to a directory, r means to read, w means to write, and x means execution.

$ ls

$ ls -og

Navigate to the Desktop directory using the cd command and list the privileges assigned to any particular file using the ls command. In our case, the file is index.html. First ‘-‘ means this is not a directory. After that rw, this file has read and writes privileges assigned to the owner but no execution rights. Next rw- refers to assigned privileges to the group and last r– means privileges assigned to others for this particular file index.html.

$ cd Desktop

$ ls –lart filename

Numeric Mode

You have to simply understand that numeric mode includes numbers to assign privileges to owners, groups, and others. Number 4 is for reading, number 2 is for write, number 3 is for execution, and number 7 is for all, e.g. read, write, and execution privileges. Now navigate to the Desktop directory and create a new file named sample.txt. List all the files residing in the Desktop directory using the simple list command and display the newly created file.

$ cd Desktop

$ touch filename

$ ls

Read Privileges

To assign read privileges only to the owner, you have to add number 4 in first place in the chmod command followed by the filename. When you execute the list command for this file, you will see that only read privileges have been assigned to an owner.

$ chmod 400 filenames

$ ls –lart filename

To give reading privileges to a group, add number 4 in second place. Read privileges have been assigned to a group.

$ chmod 040 filename

To allocate read privileges to others, add number 4 in the third location. Read privileges have been assigned to a group.

$ chmod 004 filename

To grant read privileges to the owner, group, and others at the same time, add number 4 at all locations.

$ chmod 444 filename

Writing Privileges

To offer the write privileges to the owner, you will have to add number 2 in first place in the chmod command. When you execute the list command for this file, you will see that only writing privileges have been assigned to an owner.

$ chmod 200 filenames

$ ls –lart filename

To allocate writing privileges to the group, add number 2 in the second residence. Read privileges have been assigned to a group.

$ chmod 020 filename

To assign writing privileges to others, add number 2 in third place. Read privileges have been assigned to a group.

$ chmod 002 filename

To grant writing rights to the owner, group, and others at the same time, add number 2 at all places.

$ chmod 222 filename

Execution Privileges

To grant the owner’s execution rights, you will have to add number 1 in the first place.

$ chmod 100 filenames

$ ls –lart filename

To allocate execution rights to the group, add number 1 in the second residence.

$ chmod 010 filename

To assign execution rights to others, add number 1 in third place.

$ chmod 001 filename

To grant execution rights to the owner, group, and others at the same time, add number 4 at all locations.

$ chmod 111 filename

To grant all read, write, and execution rights to the owner, group, and others simultaneously, you have to add 7 on all the places.

$ chmod 777 filename

Symbolic Mode

In this mode, you will be using symbols to give rights.

Use the +x symbol to give everyone the execution rights.

$ chmod +x filename

To take back, the execution rights add the -x symbol.

$ chmod -x filename

To grant execution rights only to the current user, which is the owner, add the u+x symbol.

$ chmod u+x filename

Similarly, groups use g+x, and others use o+x.

Take back the execution rights from all, add the ugo-x symbol. You can use a-x instead of ugo-x.

$ chmod ugo-x filename

$ chmod a-x filename

If you want to copy group rights and assign them to the user, you can use the g=u symbol.

$ chmod g=u filename

You can use the rights of one file as a reference for another file. For this, simply use the reference keyword followed by the names of files.

$ chmod --reference=filename1 filename2

If you want to assign all rights to the owner, no writing privileges to the group, and don’t want to assign any rights to others, you can simply do that by a simple concept of Read=4, write=2, and execution=1. Assign 7 to the owner as 4+2+1=7. Assign 5 to the group as 4+0+1 and assign 0 to others.

$ chmod 750 filename

To assign read permissions to all, add a+r symbol.

$ chmod a+r filename

To give read and write permissions to groups and others, add the go+rw symbol.

$ chmod go+rw filename

If you want to give everybody privileges for reading, write, execute and setup Group-ID,  add the =rwx,g+s symbol.

$ chmod =rwx,g+s filename

Conclusion

We had to bring up the basic concepts of chmod instruction in this tutorial and provided examples demonstrating how it will be used in possible situations.

]]>
How to Run Traceroute in Linux https://linuxhint.com/run_traceroute_linux/ Fri, 01 Jan 2021 20:43:53 +0000 https://linuxhint.com/?p=83875

Traceroute is a tool in Linux that allows you to investigate the routes of network packets. It can help you in identifying the limiting factor of network packet journeys. Traceroute is also useful for troubleshooting sluggish network connections. This guide shows you how to run traceroute in Linux.

About traceroute

Traceroute works by sending packets of data to the target computer, server, or website and recording any intermediate steps through which the packets travel. The output of a traceroute command will be the IP addresses and domain names through which the packets pass. These entries also show how long it takes for the packets to reach each destination. This may explain why some websites may take longer to load than others, as the number of traffic hops can vary.

Traceroute is also useful for mapping local networks. Insight into the topology and connections of the local network is found when running the tool.

Note that while using traceroute, some devices may not interact well. This could be due to routers being bugged, ISPs rate-limiting ICMP messages, devices configured not to send ICMP packets (to prevent distributed DoS attacks), etc. Some networks are also configured to block traceroute requests.

Installing traceroute

Traceroute is a powerful tool that is available for all Linux distros. Provided below is a short list of the commands to install traceroute on various distributions.

For Debian/Ubuntu and derivatives:

$ sudo apt install traceroute -y

For Fedora and derivatives:

$ sudo dnf install traceroute

For openSUSE, SUSE Linux, and derivatives:

$ sudo zypper in traceroute

For Arch Linux and derivatives:

$ sudo pacman -S traceroute

Using traceroute

The following sections show you how to use traceroute on your Linux system.

Basic Usage

The primary method for using traceroute is quite simple. All traceroute requires is the destination to perform the probing. The destination can be either a domain or an IP address.

$ traceroute linuxhint.com

$ traceroute 8.8.8.8

If a network is configured to block the traceroute signal, then this probe will be denoted with asterisks.

IPv4 or IPv6

By default, traceroute will use the default Internet Protocol with which your system is configured. To manually set the IP version, follow the procedure below.

To tell traceroute to use IPv4, use the “-4” flag:

$ traceroute -4 linuxhint.com

To tell traceroute to use IPv6, use the “-6” flag:

$ traceroute -6 linuxhint.com

Testing Ports

If there is a need to test a specific port, the port can be specified using the “-p” flag. For UDP tracing, traceroute will start with the given value and increase with each probe. For ICMP tracing, the value will determine the initial ICMP sequence value. For TCP and others, this will be the constant destination port to connect.

$ traceroute -p <port> 192.168.0.1

Hiding Device Names

In some situations, the device names in the output may make the output look messy. For more clarity, you can hide the device names from the output. To do so, use the “-n” (no mapping) flag:

$ traceroute -n linuxhint.com

Traceroute Timeout Limit

By default, traceroute waits for 5 seconds to receive a response. In certain situations, you may want to change the waiting time to be greater or less than 5 seconds. To do so, use the “-w” flag. Note that the time value is a floating-point number.

$ traceroute -w 6.0 linuxhint.com

Probing Methods

There are multiple methods that you can use to probe the remote address. To specify traceroute to use ICMP echo, use the “-I” flag:

$ traceroute -I linuxhint.com

To use TCP SYN for probing, use the “-T” flag:

$ sudo traceroute -T linuxhint.com

Setting the Maximum Number of Hops

By default, traceroute will track 30 hops. Traceroute offers the ability to manually set the number of hops to track.

Use the “-m” flag with the number of hops:

$ traceroute -I -m 10 linuxhint.com

Specifying the Interface

If there are multiple network interfaces connected to the computer, then it may help to specify the network interface to use for sending packets. To specify the network interface, use the “-i” flag:

$ sudo traceroute -i enp0s3 linuxhint.com

Defining the Number of Queries for a Hop

To define the number of queries for a hop, specify this number using the “-q” flag:

$ traceroute -I -q 4 linuxhint.com

Routing Packets through a Gateway

To route packets through a certain gateway, use the “-g” option, followed by the gateway:

$ traceroute -I -g 192.168.0.1 linuxhint.com

Traceroute Help Page

The above demonstrations are just some of the common usages of traceroute, and there are even more features for you to use. To get quick help, open the traceroute help page with the following command:

$ traceroute --help

For a fuller, more in-depth guide on all the available traceroute options, check out the man page with the following command:

$ man traceroute

Conclusion

Traceroute is a powerful tool used for network diagnostics, and there are tons of options it supports. Mastering traceroute may require some time and practice. When using this tool, you will often employ the methods described in this article.

There are more tools like traceroute out there. If you are looking to work with a similar tool in GUI, then check out Zenmap to scan a network. Zenmap is a GUI front-end for another popular network scanner called Nmap.

Happy computing!

]]>
Linux vmstat Command Tutorial For Beginners https://linuxhint.com/vmstat-command-beginners-tutorial/ Mon, 28 Dec 2020 05:25:17 +0000 https://linuxhint.com/?p=83360 If you’ve been searching for a command-line tool that can help you analyze system performance and resource usage, look no further: vmstat is the tool you want.

This tutorial will cover the basics of using the vmstat tool to monitor system performance using quick and simple examples. Although the Linux distribution in use does not matter significantly for this guide, it’s good to note that we tested it on a Debian 10.06 system.

Introduction to vmstat?

Vmstat is a command-line tool used to monitor and report resource usage on your system. It monitors the usage of system resources such as system memory, processor, and swap.

It gives real-time data reports that can help system administrators and Linux troubleshooters quickly and easily determine causes of performance issues and high memory usage in a system.

How To Use vmstat

To use the vmstat tool, execute the command vmstat in the terminal. You will get an output similar to the one shown below:

Using the command vmstat with no arguments outputs an average view of system resource usage since the last system reboot. To filter precise information, use the command:

vmstat <interval> <count>

After using the above syntax, vmstat reports the average system used since the last reboot subsequently until the count value is reached. For example, if the count value is 10, vmstat will display system information usage 10 times. The command also specifies that vmstat should report data every interval value (in seconds).

Vmstat usage

Depending on the information or type of problem you are diagnosing, you will often run vmstat with a small interval value. Consider the following vmstat output. Report every 2 seconds for 15 times.

You can also execute the vmstat command without the count argument. Doing that will give current system usage reports in real-time for the specified interval.

For example:

It is a better option to output the report from vmstat to a log file to read and analyze later. To stop a running vmstat session, press the CTRL + C keys.

By default, vmstat will show memory reports in kilobytes with a single kilobyte equivalent to 1024 bytes. To configure vmstat to use 1 kilobyte as 1000 bytes, use the command:

vmstat -S k 1 10

Where you want to use megabytes to display memory size, use the -S m argument, and Vmstat will report one megabyte as equivalent to 1000 kilobytes.

Understanding vmstat output

As we mentioned, vmstat reports the up-to-date system state. It provides useful information concerning the condition of the system, which is helpful in troubleshooting performance issues.

Given this, it’s important to understand what the output from vmstat represents.

Vmstat groups the output information in columns. These columns contain related information depending on the command specified. The following are some of the columns from a vmstat output.

1: Procs Column

The procs table represents the number of jobs in the queue (jobs waiting to run). This column can help you determine the processes blocking the system from executing other jobs.

Inside the procs column, you will find r and b columns. These display the total number of processes waiting to go into the processor and the total number of functions in a sleep state.

In most cases, values in the b column are 0.

2: Memory Column

The memory column displays information on the total amount of free and used memory in the system. This output is similar to the free command.
Under the Memory column, there are four other columns:

  • Swapd
  • Free
  • Buff
  • Cache

The swap or swapd tab displays the amount of memory already exchanged (swapped) out into a swap file or swap partition.

In the free column, you will find information on the amount of unused memory. (unallocated memory).

The buffers column displays information on the amount of memory in use. (allocated memory).

Finally, in the cache column, you’ll find information about allocated memory that can be exchanged to the disk if the resources are needed.

3: Swap Column

Next, we have the swap column used to report the speed at which memory gets swapped to and from the swap file or partition.

Using the swapd and total disk activity, vmstat allows you to calculate the disk activity relationship with the swap system.

In the swap column, you will also find the si and columns used to show the amount of memory transferred from swap to main memory every second and the amount of memory moved to swap from main memory every second.

4: I/O Column

In the next column, you will find information regarding system input and output actions, expressed in reading and write per block. Under the I/O column are bi and bo columns, representing the number of blocks received from the disk per second and the number of blocks sent to disk per second, respectively.

5: System Column

The system column displays information on the total number of system processes per second. System column has two more columns, i.e., in and cs. The first column shows system interrupts (includes interrupts from the system clock) per second. The cs column indicates the number of context switches made by the system to process all tasks successfully.

6: CPU Column

The last column is the CPU. This column displays the CPU resource usage. The CPU column has four main columns under it.

  • us
  • sv
  • id
  • wa

The first column (us) represents the total amount of time used by the processor on tasks created by the user.

The next column (sv) displays information related to the time the processor uses on kernel processes.

The id column shows the amount of time the processor spent on idle.

Finally, the (wa) column shows the total amount of time used by the processor on wait I/O operations.

Adding all values in the CPU columns adds up to 100, representing a percentage of available time.

Conclusion

In this tutorial, we learned how to use vmstat, a tool used to report system resource usage. We also covered how it works and how we can query for specific information. We also discussed how to understand vmstat output and use it to troubleshoot system resource problems.

]]>
How To Use Strace On Linux https://linuxhint.com/use-strace-linux/ Sun, 27 Dec 2020 13:52:28 +0000 https://linuxhint.com/?p=83143 When working with Linux systems, you’ll often need to inspect and understand the actions performed by processes and the system calls carried out by their execution.

When it comes to performing such tasks, the Linux kernel provides features such as ptrace to debug and diagnose processes.

This article discusses how to use the strace tool to trace, monitor, and debug processes interacting with the Kernel.

What Are System Calls?

Before we discuss how to use strace, you need to understand what we are looking for and how they work. That means we should l go over the basics of Linux System calls.

A system call is a programmatic method through which a program can request a service from the system’s Kernel. That is the process we will use to inspect the actions between user processes and the Linux kernel.

Anytime a user executes a program that makes a read, write, kill, exit, bind, etc., request, they are making a system call. There is a wide range of system calls used by programs to perform various tasks such as networking, reading and writing to files, initializing and terminating processes, and much more.

Think of system calls as functions—they behave similarly—because they can accept arguments and return values. The main difference between system calls and normal operation is that system calls can directly interact with the Kernel. System calls use a trap mechanism to navigate between user space and the Kernel.

In the Linux system, this mechanism is well hidden from the users by libraries such as Glibc.

NOTE: There is a lot more to system calls and kernel interactions than what we’ve discussed in this tutorial. Please refer to the manual pages for more information.

https://linkfy.to/syscalls

https://linkfy.to/trapmanual

How to Install strace on Linux

Although strace tools don’t come pre-installed by default in major Linux distributions, it is available in most official repositories of these distributions; you can install it easily using default package managers.

NOTE: Although we won’t cover how to install strace on all systems, we’ll discuss how to do so with major package managers such as apt, dnf, pacman, and yum

1: Debian (apt) Installation

Install strace using the command:

apt-get install strace -y

2: RedHat Family (dnf and yum)

To install strace using yum package manager, enter the command:

yum install strace

For dnf package manager, enter the command:

dnf install strace

3: Arch Linux (pacman)

For Arch Linux users, you can install strace with the command:

pacman -S strace

Now that you have strace installed and running, we can move on and learn how to use

Basic Strace Usage: A How-to Guide

Let’s discuss basic strace usage and understand the basic output of the command and how we can use it.

NOTE: Strace output such as system calls names, corresponding arguments, and return values get handled by the standard error file descriptor (stderr).

The basic way to use strace is by calling the strace utility followed by the program’s name, whose behavior we want to understand.

Here’s an example of that using the ls command:

Wow! That is a lot of output for a simple command such as ls.

Although we cannot discuss all the output from the strace command, we can distill and understand its meaning.

If you consider the first line in the output above, you will notice the following features.

  • The name of the system call
  • The arguments passed to the system call enclosed in parenthesis.
  • The return value from the system call

Hence, in the first line, the system call is execve (execute program using the specified array of arguments), the arguments of the system call are (“/bin/ls”, [“ls”, “/”], 0x7fffc4b277a8 /* 13 vars */) and a return value of 0.

https://linkfy.to/execve

The execve system calls execute the binary we want to use, in this case, located in (/bin/ls) and the array of arguments being the path we want to list contents.

You will also notice a notation enclosed with a forward slash and an asterisk. For our example:

/* 13 vars */

The above output indicates the number of variables added as a result of calling the process. The environment inside the execv function is accessed by using the environ external variable defined as:

int main(int argc, char *argv[], char *envp[])

The final output is the return value, which is 0 in this case.

You’ll also notice that most lines of the strace output follow a similar pattern we discussed above.

How to Trace Specific System calls

Although strace gives a lot of information regarding programs system calls, most instances will call on you to filter specific system calls. To do this, we pass the -e flag to the strace command followed by the name of the system call we need.

How about looking at the read system calls for the ls command. For example:

strace -e read ls

You will notice that this only displays only read system calls.

The read system call accepts three arguments: file descriptor, buffer, and the number of bytes. The system call then reads up to the count bytes from the passed file descriptor argument into the buffer.

https://linkfy.to/readsyscall

Summary of System Calls

Strace also allows us to get a summary of system calls made by a process. By passing the -c or –summary-only argument, we can get an output such as the one shown below:

The command filters and arranges the output more efficiently than the normal strace output. To get both summary and normal strace output, pass the -C argument.

How To Use Strace With Running Processes

At other times, you will need a trace of a running process. Up to this point, we have only used strace a single command. To trace a running process, we can use the -p argument followed by the Process ID (PID) process to attach strace to it.

You can get the PID of a running process by using the top and grep, ps, htop, pidof, or other system monitoring tools.

For example, to get the PID of the apache process, we can use:

ps -ax | grep -i apache2

That should give you the PID of the apache2 process (PID 3514 in this case), and we can use it to attach it to strace.

That should display an output similar to the one shown below.

Strace will continuously trace the attached process and show output as the attached process executes system calls. To terminate the trace, press CTRL + C, which detaches the process from the strace.

How to Save Strace Output to Files

We can also redirect the output of strace to a file as an argument. Using the -o flag followed by the file path as an argument, we can save strace logs.

For example:

strace -p 3514 -o ~/Desktop/apache_trace

Once the file is saved, you can later monitor and analyze it.

Conclusion

In this guide, we learned how to install and use strace on Major Linux distributions. Now that you understand system calls and how processes work, you can use strace to monitor and debug a running system process running.

The concepts learned in this tutorial are very useful, mainly because you can use what you’ve learned to monitor if anyone is tampering with system processes.

]]>
Bash Tree Command https://linuxhint.com/bash-tree-command/ Thu, 03 Dec 2020 19:32:42 +0000 https://linuxhint.com/?p=79225 The intention of this tutorial is to understand the JSON data and how to parse JSON data in C++. We will discuss JSON data, Object, Array, JSON syntax, and then go through several working examples to understand the parsing mechanism of JSON data in C++.

The “tree” command is a very extensively used Bash command in Linux. It is used to display the contents of any desired directory of your computer system in the form of a tree structure. By using this tree structure, you can easily find out the paths of your files and directories, check their access permissions, and view the hidden files and directories. Therefore, today we will be talking about using the Bash “tree” command in Linux Mint 20 by sharing some examples with you.

Bash Tree Command in Linux Mint 20:

To use the Bash “tree” command in Linux Mint 20, you first need to install it by running this command:

$ sudo apt install tree

It would be nice if you can update your system before running this command. Once the “tree” command is successfully installed on your Linux Mint 20 system, you will get the following messages on your terminal:

Now to check whether the Bash “tree” command is actually residing there on your Linux Mint 20 system or not, you can check its version by running the command stated below:

$ tree --version

The version of the Bash “tree” command that we have managed to install just now is highlighted in the following image:

After doing this, you can check out the syntax and all the available options for this command so that you can use it effectively. You can look for this information by running the command stated below:

$ tree --help

Executing this command will display all the necessary information regarding the Bash “tree” command, including its syntax that you will need to work with this command without any difficulty. You can spend some time on it to grasp all the available options nicely.

After performing these steps, we would like to share with you some of the most useful examples of using the Bash “tree” command in Linux Mint 20.

Example # 1: Display the contents of a Directory in a Tree-like Structure:

The tree structures are generally easier to visualize and interpret as compared with the regular textual representation. Therefore, if you have a directory that contains lots of different files and sub-directories in it, then you should prefer to view its contents in a tree-like structure. This can easily be done by running the tree command, as shown below:

$ sudo tree

The tree structure of our current working directory is shown in the following image. A point to be noted over here is that the simple “tree” command does not display the hidden files and directories. That is why the number of files and directories displayed in the output of this command is very little.

Example # 2: Display the Hidden Files and Directories with the Tree Command:

Unlike the simple “tree”, you may also want to have a look at the hidden files and directories. You can do this simply by running the “tree” command with the “-a” flag in the manner shown below:

$ sudo tree –a

You can compare the output of this command with the output shown in example # 1, and you will be able to realize that the number of files and directories is far greater than the one shown above. It is so because this time, the “tree” command has also displayed the hidden files and directories.

Example # 3: Display the Files and Directories along with their Complete Paths:

Instead of only displaying the names of the files and directories, you may also wish to find out their exact paths. You can do this simply by combining the “tree” command with the “-f” flag in the following manner:

$ sudo tree –f

The paths of all the files and directories within our current working directory are shown below in the form of a tree structure. If you would have been running the “tree” command in a directory other than the “Home” directory, then the concept of paths would be clearer. However, in our case, since we ran the “tree” command while staying within the “Home” directory, that is why you can only see “./” instead of file or directory path since it represents the “Home” directory.

Example # 4: Print the Directory Tree in XML Representation:

XML or Extensible Markup Language has a specific syntax in which it represents our files and directories. Therefore, if you wish to print your directory tree in an XML representation, then you can do this by pairing the “-X” flag with the “tree” command in the following manner:

$ sudo tree –X

The XML representation of our directory tree is shown in the image below:

Example # 5: Display the Files and Directories along with their Access Permissions:

File and directory permissions are considered very important, especially if we wish to deal with the access control policies within an operating system. If you want the file and directory permissions to be displayed in your directory tree, then you will have to run the “tree” command with the “-p” flag.

$ sudo tree –p

The “read”, “write”, and “execute” permissions are shown before each file and directory name in our directory structure as shown in the following image. Moreover, the directory permissions also include a “d” flag that indicates that the following name is of a directory and not of a file.

Conclusion:

In today’s article, we shared with you the method of installing the Bash “tree” command on your Linux Mint 20 system. We demonstrated the method of verifying its installation and also accessing its help pages. Then we shared with you the five most important scenarios in which the “tree” command can be used very effectively. Apart from these five scenarios, there are lots of other use cases of the Bash “tree” command too. In a nutshell, this Bash command is considered extremely helpful while dealing with the Linux based operating systems.

]]>
How to Use the “cat” Command in Bash? https://linuxhint.com/cat-command-bash/ Tue, 01 Dec 2020 10:30:43 +0000 https://linuxhint.com/?p=78942

The “cat” command in Bash stands for “concatenate”. This command is very frequently used for viewing, creating, and appending files in Linux. Today, we will explain to you the usage of this command in Bash in Linux Mint 20 by sharing some examples.

Method of Using the “cat” Command in Bash:

For using the “cat” command in Bash, we will show you six different examples. For demonstrating these examples, we have created two different text files named cat1.txt and cat2.txt with some random text. We will be using these text files in our examples below:

Example # 1: Displaying the Contents of a File:

If you want to display the contents of a file with the “cat” command in Bash, we have to proceed by executing this command:

$ cat SampleFile

Here, you have to replace SampleFile with the name of the file which you want to be displayed on the terminal. We wanted to display the contents of the cat1.txt file that is why we have replaced SampleFile with cat1.txt.

The text that we wrote in our cat1.txt file is shown in the following image:

Example # 2: Displaying the Contents of Multiple Files:

If you have multiple files and you want to display the contents of all these files at once, then you have to proceed by executing this command:

$ cat SampleFile1 SampleFile2

Here, you have to replace SampleFile1 and SampleFile2 with the names of the files whose contents you want to be displayed on your terminal. We wanted to display the contents of the cat1.txt and cat2.txt files; that is why we have replaced SampleFile1 with cat1.txt and SampleFile2 with cat2.txt. You can also have more than two file names in this command if you want to display the contents of more than two files on the terminal.

The contents of our two files will be displayed in separate lines, as shown in the following image:

Example # 3: Displaying the Contents of Multiple Files Separated by a “$” Symbol:

You can see from the example shown above that we can display the contents of more than one file at once on our terminal. However, there is no clear distinction or separation in the file contents. In other words, you cannot distinguish which contents belong to which file. Therefore, we can use the “$” separator, which will be inserted at the end of the contents of each file. In this way, you will clearly be able to see where the content of one file ends.

For doing this, we will have to use the “-e” flag in the following manner:

$ cat –e SampleFile1 SampleFile2

Here, you have to replace SampleFile1 and SampleFile2 with the names of the files whose contents you want to be displayed separated by a “$” symbol on your terminal. We wanted to display the contents of the cat1.txt and cat2.txt files separated by a “$” symbol; that is why we have replaced SampleFile1 with cat1.txt and SampleFile2 with cat2.txt. You can also have more than two file names in this command if you want to display the contents of more than two files separated by a “$” symbol on the terminal.

The contents of our two files will be displayed on the terminal separated by a “$” symbol as shown in the following image:

Example # 4: Creating a New File with the “cat” command:

Other than displaying the contents of a file, the “cat” command is also capable of creating a new file. For that, we need to proceed by executing this command:

$ cat >SampleFile

Here, you have to replace SampleFile with the name of the file that you want to create with the “cat” command. We wanted to create a file named cat3, that is why we have replaced SampleFile with cat3.

When you press the Enter key to execute this command, you will see a prompt on your terminal, which will indicate that the “cat” command is asking you to enter some text into your file. You can add any text of your choice in it as we did and then press the Ctrl+ d key combination to save the newly created file.

Now you can also check if a file with the desired text has been created or not by running this command:

$ cat SampleFile


We have replaced SampleFile with cat3 to display its contents, as shown in the image below:

Example # 5: Displaying Line Numbers along with the Contents of a File:

If you have a very large file, then it is always convenient to view it with line numbers. To display the line numbers along with the contents of a file, you have to proceed by executing this command:

$ cat –n SampleFile


We have replaced SampleFile with cat3 since we wanted this file’s contents to be displayed with line numbers, as shown in the image below:

Example # 6: Appending the Contents of Files:

If you ever want to append the contents of one file at the end of another, then you can proceed by executing this command:

$ cat SampleFile1 >> SampleFile2

Here, you have to replace SampleFile1 with the name of the file whose contents you want to append and SampleFile2 with the name of the file where you want to append the contents. We have replaced SampleFile1 with cat1.txt and SampleFile2 with cat2.txt. It means that our text “Hello World!” will be appended at the end of our text, “We want to test the “cat” command.”

Running this command will simply append the contents of one file to another without displaying anything on the terminal.

You can confirm it by checking the contents of SampleFile2 or cat2.txt in our case as follows:

$ cat SampleFile2.txt


The contents of our appended file i.e. cat2.txt are shown in the image below:

Conclusion:

This is how you can learn the usage of the “cat” command in Linux Mint 20 by going through all the examples that we discussed today.

]]>
How to Use the “wc” Command in Bash? https://linuxhint.com/wc-command-bash/ Tue, 01 Dec 2020 10:18:29 +0000 https://linuxhint.com/?p=78918

The “wc” or the word count command in Bash is considered extremely useful as it helps in finding out various statistics of a file. This command can be used in multiple different variations. However, in this guide, we’re going to learn the basic usage of this command in Bash.

Method of Using the “wc” Command in Bash in Linux Mint 20:

Before starting to use the “wc” command in Bash, we would first like to show you the version of this command that is installed on our Linux Mint 20 system.

$ wc --version


To check the version of the “wc” command installed on our system, we have shown the output of the above-mentioned command in the image below:

We also want to state here that for demonstrating the usage of the “wc” command in Bash in Linux Mint 20, we have created a random file named wc.txt. We have used the very same file in all the eight examples described below. You can see the contents of this file by running this command.

$ cat wc.txt


The content of this dummy file is shown in the following image:

After showing this, we are all set to explain to you some examples regarding the usage of the “wc” command in Bash in Linux Mint 20.

Example # 1: Displaying the Number of Lines, Words, Characters, and the Name of a File:

If you want to display the number of lines, words, characters, and the name of a file in Linux Mint 20, then you can run the “wc” command without any additional flags in this manner:

$ wc File

Here, you should replace the File with the name of the file whose line count, word count, character count, and name you want to be displayed on your terminal. We have replaced it with wc.txt, i.e., the name of our dummy file.

The output of the default “wc” command is shown below:

Here, the first column represents the line count; the second shows the word count, the third displays the character count, whereas the fourth states the name of the file.

Example # 2: Printing only the Number of Words and the Name of a File:

If you only want to print the total number of words in a file along with its name, then you can use the “wc” command with the “-w” flag.

$ wcw File

Here, you should replace the File with the name of the file whose word count and name you want to be displayed on your terminal. We have replaced it with wc.txt, i.e., the name of our dummy file.

The modification of output of the “wc” command is shown below:

Example # 3: Printing only the Number of Lines and the Name of a File:

If you only want to print the total number of lines in a file along with its name, then you can use the“-l” flag along with the “wc” command.

$ wc –l File

Here, you should replace the File with the name of the file whose line count and name you want to be displayed on your terminal. We have replaced it with wc.txt, i.e., the name of our dummy file.

The modification of output of the “wc” command is shown below:

Example # 4: Printing only the Number of Characters and the Name of a File:

If you only want to print the total number of characters in a file along with its name, then you can use the “wc” command with the “-m” flag.

$ wc –m File

Here, you should replace File with the name of the file whose character count and name you want to be displayed on your terminal. We have replaced it with wc.txt, i.e., the name of our dummy file.

The modification of output of the “wc” command is shown below:

Example # 5: Printing only the Number of Bytes and the Name of a File:

If you only want to print the total number of bytes in a file along with its name, then you can use the “wc” command with the “-c” flag.

$ wc –c File

Here, you should replace the File with the name of the file whose byte count and name you want to be displayed on your terminal. We have replaced it with wc.txt, i.e., the name of our dummy file.

The modification of output of the “wc” command is shown below:

Example # 6: Printing only the Length of the Longest Line (number of characters in the longest line) and the Name of a File:
If you just want to display the longest line length and name of a file, then you can use the “wc” command with the “-L” flag.

$ wc –L File

Here, you should replace File with the name of the file whose longest line’s character count and name you want to be displayed on your terminal. We have replaced it with wc.txt, i.e., the name of our dummy file.

The modification of output of the “wc” command is shown below:

Example # 7: Printing the Total Number of Files and Folders in the Current Directory:

The “wc” command can also be combined with the “ls” command to print the total number of files and folders in a directory in the following manner:

$ ls | wc –l


The total number of files and folders in our current directory, as shown in the image below:

Example # 8: Displaying the Number of Lines, Words, Characters, and the Names of more than one file along with the Total Count:

If you want to display the line count, word count, character count, and names of more than one file, then you can run the “wc” command in the following manner:

$ wc File1 File2

Here, you should replace File1 and File2 with the exact names of the files whose statistics you want to be displayed on your terminal. We have replaced them with wc.txt and abc.txt, i.e., the names of our dummy files. You can even mention the names of more than two files.

The modification of output of the “wc” command is shown below:

Here, the last row represents the total line count, word count, and character count of both of our files.

Conclusion:

By going through this tutorial on the usage of the “wc” command in Bash, you can easily use this command to find all the necessary details about your files in Linux Mint 20.

]]>
Top 10 Tools to Automate Linux Admin Tasks https://linuxhint.com/automate-linux-admin-tasks-tools/ Sun, 29 Nov 2020 13:20:03 +0000 https://linuxhint.com/?p=78531

If you are a Linux administrator, or you want to become one, there are certain tasks that can become repetitive and boring. In fact, back in the day, some tasks were so incredibly repetitive that it became very hard to keep track of all the servers; this is why automation tools were created to help with such tasks. These tools help you manage and administer different servers or systems at once, and some of them allow you to do a particular task with only a click or a command line. These tools mentioned below will definitely help you automate some of the tasks of a system administrator so that you can concentrate on other interesting concepts and tasks.

Here are the top 10 Linux Admins to boost office productivity and ease of access. Click on the links to visit the homepage.

1. Puppet

Puppet is one of the largest open-source system administration tools, which helps you automate several tasks. It is used by major enterprises to configure and administer their servers. It monitors the network continuously for any alterations, and it can automatically configure any changes that may happen. It also helps to create and manage users efficiently. It also allows different system administrators and developers to work together, which makes the tasks of each individual easier.

Puppet automates server set-up, program installation as well as system management. It is not only supported on Linux but also on Windows and macOS. It is not very hard to set up or use. It is a paid software, but since so many companies use it, it is worth the price.

$ sudo apt-get install puppet-agent

2. CFEngine

CFEngine is an automation tool, which helps you with managing your infrastructure easily. It can search for system errors efficiently and fix them automatically, without the need for any user interaction. It can also automatically perform package updates across hundreds of servers at once. It can also help you do several tasks such as process management, schedule management, reporting and compliance, service management, password management, application deployment, etc. It is well known due to its ability to self-heal and its quick response times. It is relatively easy to download and set up and also easy to use once installed. It is not free or open-source, but since it is so well known, organizations are willing to buy it for efficiency.

3. Nagios

Nagios, also known as Nagios Core, is a management tool made for Linux system administration tasks that helps you automate and manage all systems in your infrastructure. It provides a thorough report on network traffic, which helps in monitoring any system threats that might damage the health of the network. It can help you manage printers, routers, etc. If it finds a fault in a system, it automatically restarts it to fix it. It is not free, but many enterprises like to use it. It is not very easy to work with, as it has a very complicated installation process, but once it is set up, it is very efficient. You can download it directly from their website and start working with it.

4. Cacti

Cacti is an open-source, web-based network monitoring tool for Linux. It works in real-time, which makes it very efficient at finding any discrepancy in the system quickly. It collects data about the different systems under it and presents it in the form of an easy to understand graph format. It collects data from several different data centers and stores them in a MySQL database, which makes it easier for administers to monitor the server load, network performance, and such tasks.

It also has a user management tool, which you can use to give access to certain areas of the tools to users that you can add. Cacti is quite hard to install and set up, it requires some expert help, but it is easy to use once it has been installed. It is a paid service, and it is not the easiest to use.

5. Amanda

Amanda is one of the oldest Linux backup tools on the market. It is open-source, and it is widely popular. Using this tool, you can automate, schedule, and track backups. It can backup multiple hosts on your network at the same time. The backups can be stored anywhere, from disks, tapes, or optical media. It is not the easiest to set-up, but once it is running, it consistently backs up data to ensure that nothing is lost. It is normally free, but it has an enterprise version, which is not. The enterprise version gives you some extra tools such as Centralized backup of heterogeneous systems, support for a large collection of OS, etc.

6. Bacula

Bacula is a collective set of programs that can manage the backup, recovery, and verification of computer data from different networks. It can help you backup different types of media as data. It can work from a single computer and manage hundreds of computers at once. There is a very user-friendly admin workstation, where you can either use command lines or a GUI to interact with the software. It also consists of a backup server, which is where the background application will run to automate and schedule the data backup.

Bacula is not a very easy tool to use; it has a complicated system to set up and does not have as many features as the previous one. However, it is simple and easy to use once it is set up. It has a free version; however, the enterprise version is paid.

7. SaltStack

Salt or SaltStack is a Python-based open-source software, which is used for IT automation and remote task execution. It ensures high-speed data collection and system management for massive infrastructure. Salt is primarily used for remote tasks, which can be as simple as asking a web server to show a webpage and as complex as using a shell session to issue commands.

Salt is generally used by massive enterprises because it is efficient at managing all servers at once. With a single command line or a click of a button, you could update the software on all servers. It has high security as it uses data encryption to protect all data that is processed through it. It has a relatively easy installation process, and also it is easy to use. It is not free, but the price is worth it as it is very efficient.

8. Cockpit

The Cockpit is an open-source server manager, which is very easy to use. It is developed by Red Hat, one of the leading open-source software producers. The cockpit is a web-based GUI, which helps you automate several Linux administrative tasks. It helps you administer several servers at the same time.

Cockpit allows you to automate system software updates and security updates. It also allows you to do tasks such as software installations and user management. You can install Cockpit on most Linux distros, but it is pre-installed on CentOS.

9. cPanel

It is the most reliable web-based administrative tool which lets you manage several things such as websites, domains, apps, etc. One of the key features of cPanel is its integration with WHM for the automation of daily tasks using hooks. The hook system helps you to automatically create various items in your servers, such as user accounts, emails, logs, MySQL databases, and more.

The integration with WHMCS allows for automatic billing management. It has a lot of features, and you can use it with a powerful GUI to manage all kinds of hosting services and more. It is quite easy to install and use. It is not free, but it is very useful, so it is worth the money.

10. phpMyAdmin

phpMyAdmin is a PHP-based open-source web app. It is free to use, and you can use it on a web browser for creating and managing MySQL databases. It is preferred by students and junior system admins because of it’s easy to use interface. It is used for several administrative tasks, such as automating MySQL databases, along with creating, deleting, and altering them. It can work with different operating systems as well. It can run MySQL queries, optimize, repair, and check tables and do other tasks related to database management. It is easy to install, and since it is free, it is available to everyone for use.

So, these are the top 10 tools to automate Linux admins tasks. Feel free to share with us your view about the above tools at @linuxhint and @SwapTirthakar.

]]>
How to Use hexdump Command in Linux? https://linuxhint.com/how-to-use-hexdump-command-in-linux/ Wed, 18 Nov 2020 18:51:49 +0000 https://linuxhint.com/?p=77234 Hexdump is a powerful tool in Linux systems that are mostly used by developers and app debuggers. It can convert input files and data into a pleasant and readable format.

Here’s a real-life example where hexdump may be helpful. If you’re working with binary data, this will be very difficult to understand. For ease, you can quickly turn the binary data into hexadecimal or decimal.

In this guide, check out how to use hexdump command in Linux.

Hexdump in Linux

Hexdump is a simple yet useful program that’s written in C language. That’s why professional C programmers may find its usage easy. However, even if you’re not experienced in C programming, you can still use hexdump for your purpose.

Hexdump comes pre-installed in any Linux distro. In this guide, I’ll be using Ubuntu for demonstration purposes.

Hexdump usage

For demonstrating the usage of hexdump, I’ve created a sample text file dummy.txt.

$ cat dummy.txt

We’ll be passing this file to hexdump to convert its content into various formats of output.

One-byte octal display

The following hexdump command will print the input data in hexadecimal format. In the output, each line contains 16 space-separated bytes of input data, each having 3 columns and zero-filled, in octal.

$ hexdump -b <input_file_content>

One-byte character display

The following hexdump command will display the input data in hexadecimal format. In the output, each line contains 16 space-separated characters of input data, each having 3 columns and space-filled.

$ hexdump -c <input_file_content>

Canonical hex + ASCII display

The following hexdump command will display the input data in hexadecimal. In the output, each line contains 16 space-separated hexadecimal bytes, each having 2 columns. The following content will be the same bytes in %_p format enclosed in “|” characters.

$ hexdump -C <input_file_content>

Two-byte decimal display

The following hexdump command will display the input data in hexadecimal format. In the output, each line contains 8 space-separated 2 bytes units of input data, each having 5 columns and zero-filled, in unsigned decimal.

$ hexdump -d <input_file_content>

Two-byte octal display

The following hexdump command will print the input data in hexadecimal format. In the output, each line contains 8 space-separated 2 bytes of input data, each with 6 columns and zero-filled, in octal.

$ hexdump -o <input_file_content>

Two-byte hexadecimal display

The following hexdump command will print the input data in hexadecimal format. In the output, each line contains 8 space-separated 2 bytes of input data, each with 4 columns and zero-filled, in hexadecimal.

$ hexdump -x <input_file_content>

Display all input

When using hexdump, it’ll replace the content of repeated lines with a single asterisk. If you want to force hexdump to output all the contents, then use the “-v” flag.

$ cat dummy.txt

$ hexdump -b dummy.txt

$ hexdump -v -b <input_file_content>

Limit amount of bytes

Hexdump supports the option of deciding a specific number of bytes from a file to hexdump. To specify the amount, use the flag “-s” followed by the byte amount.

$ hexdump -s 2 -c <input_file_content>

Final thought

The examples demonstrated here are the ways you’ll mostly use hexdump. For complete information on hexdump, the man page is one of the best resources.

$ man hexdump

Hexdump is a powerful tool if you know when and how to use it. However, tools aren’t always the answer when it comes to debugging. Check out how to debug a bash script. If you’re into NodeJS, then check out how to use the NodeJS debugger.

Enjoy!

]]>
Zip and Unzip Commands in Linux https://linuxhint.com/zip_and_unzip_commands_linux/ Sun, 08 Nov 2020 17:13:38 +0000 https://linuxhint.com/?p=76125

Zip is a popular cross-platform command used for compressing and archiving data. Compression saves space by shrinking the size of data while archiving makes the transfer of data easier by combining multiple files or directories into a single file. Consider, if we have to transfer 5 files over the internet, each with size 50 megabytes; transferring all the files one by one could take a long time. Compressing the files to reduce the size up to 25MB, and then archiving all of them in a single file will make it much quicker to transfer the files than when they are uncompressed. Zip is the most widely used utility for archiving and compressing files, while the unzip is used for extracting and decompressing the zipped files.

In this article, we will look at the zip and unzip commands in Linux, along with their command-line options and examples.

Prerequisites

  • Ubuntu or Debian system
  • Zip and unzip utilities installed

Note: The commands mentioned in this article have been tested on Ubuntu 20.04 LTS (Focal Fossa). The same commands are also applicable to Debian distribution.

Installing Zip and Unzip

By default, zip and unzip packages are installed in Ubuntu systems. In case these are missing from your system, you can install them easily. Launch the Terminal using the Ctrl+Alt+T keyboard. Then to install zip, issue the following in Terminal:

$ sudo apt install zip

To install unzip, issue the below command in Terminal:

$ sudo apt install unzip

There are some scenarios where you may be required to zip files:

  • To save storage space, as zipping compresses the file size
  • Transferring large files over e-mail
  • Uploading or downloading files at a quicker speed
  • To save bandwidth

ZIP Command in Linux

To create a zip file, you will need to provide the name for the zipped archive and the files that need to be included in the zip.

$ zip options zip_file file1 file2...

Zip single file

To zip a single file named testfile.txt; to a zip file named test.zip, the command would be:

$ zip test.zip testfile.txt


The above command will compress the specified file in the current directory while leaving the original file behind.

To confirm if the zip file has been created, issue the command in the Terminal below:

$ ls -l

Zip multiple files

You can also zip multiple files with the zip command. Let’s create some files named testfile1.txttestfile2.txttestfile3.txt, and testfile4.txt using the following command in the Terminal:

$ sudo touch testfile1.txt testfile2.txt testfile3.txt testfile4.txt

Now to zip these files in a single file, named files.zip, issue the following command in the Terminal:

$ zip files.zip testfile1.txt testfile2.txt testfile3.txt testfile4.txt

You can also use the wildcard to specify multiple files having the same extension. For instance, to zip all the files ending with .txt extension in a zip file, named files1.zip, issue the following command in the Terminal:

$ zip files1.zip *.txt

Zip a file to a different directory

If you need to zip a file to some directory other than the current directory, use the following syntax:

$ zip /path/to/directory.zip_file filename

For instance, to zip testfile.txt file to Documents/docs/ directory named as test.zip, the command would be:

$ zip Documents/docs/test.zip testfile.txt

Add file to an existing zip

You can also add a file to a pre-existing zip file. Use the following syntax to do so:

$ zip -u zip_file filename

Let’s say you have a zip file (files1.zip), and you want to include one more file (testfile4.txt) in it, the command, in this case, would be:

$ zip -u files1.zip testfile4.txt

Remove a file from a zip file

Similarly, you can also remove a file from an already existing zip file. Use the following syntax to do so:

$ zip -d zip_file filename

Let’s say you have a zip file (files1.zip), and you want to remove a file (testfile1.txt) from it, the command, in this case, would be:

$ zip -d files1.zip testfile1.txt

Zip files in quiet mode

If you do not want to display the output of the zip command, use the -q (quiet) option with the zip command as follows:

$ zip -q zip_file filename

For instance, while zipping testfile.txt, you can suppress the output with the following command:

$ zip -q test.zip testfile.txt

In the following screenshot, you can see the zip command output that has not been displayed on the Terminal.

Deleting original files after zipping

By default, zip keeps the original file along with the compressed file. However, using the -m option with the zip command, you can delete the original files after creating their zipped file.

$ zip -m zip_file filename

For instance, the following command will delete the testfile.txt after creating its zipped file, test.zip.

$ zip -m test.zip testfile.txt

Zip directories

To zip directories in your Linux system, use the -r (recursive) option with the zip command. The -r option will zip the directories recursively, i.e., including contents of subdirectories.

$ zip -r zip_file directoryname

For instance, to zip the Documents directory recursively to the test.zip file, the command would be:

$ zip -r test.zip Documents/

This command will zip the Documents directory, along with all the subdirectories and the files included within it.

Setting the level of compression

You can also set the level of compression to apply to the files being zipped. The level of compression ranges from 0 to 9, where 6 is the default value, 0 is the lowest value, and 9 is the highest value of compression.

For instance, to zip all text files to files1.zip using the highest compression value , the command would be:

$ zip -9 files1.zip *.txt


Similarly, to zip all text files to files2.zip using the lowest compression value -0, the command would be:

$ zip -0 files2.zip *.txt


The following is the output of the ls command after creating the zip files. If we compare the sizes of both zip files, you can see files1.zip, which was compressed using compression level 9, has less size as compared to files2.zip, which was compressed using compression level 0.

Create a password-protected zip file

You can also create password-protected zip files using the -e option with the zip command as follows:

$ zip -e zip_file filename

For instance, the following command will zip all text files in files3.zip, then ask for a password. Set any password and press Enter. Then verify this password by re-typing it and pressing Enter.

$ zip -e files3.zip *.txt

Adding passwords to zip files with the zipcloak

In the previous example, we have created a password-protected zip file. But what if you have created a zip file and forgot to set the password. With zipcloak command, you can set a password to a zip file at any time.

$ zipcloak zip_file

For instance, to set a password to an already created zip file named files.zip, the command would be:

$ zipcloak files.zip

You will be asked for a password. Type any password and press Enter. Then verify this password by re-typing it and pressing Enter.

View file details with the zipdetails command

Zipdetails command shows detailed information about the zipped file. The information it displays is about record structure rather than of the compressed data. To find detailed information about the zipped file, type zipdetails followed by the zipped file name, as shown below:

$ zipdetails zip_file

For instance, to find detailed information about a zipped file, test.zip, the command would be:

$ zipdetails test.zip

In the output, you will see a lot of information about your zipped file.

Search inside the file with the zipgrep command

The zipgrep command allows us to search for a given text within files inside the zipped file without extracting it. If a zip file is password-protected, then you will have to first enter the password for it. To search for text inside the zip file, use the following syntax:

$ zipgrep expression zip_file

For instance, to search which files inside the zip file test.zip contains the word gateway, the command would be:

$ zipgrep gateway test.zip

The output is as follows. You can see two files iplist.text and iplist inside the test.zip contains the word gateway.


To search for a text from a specific file inside the zip file, you can also add it:

$ zipgrep expression zip_file filename

For instance, the following command will search for the word gateway from only a specific file iplist inside the zip file test.zip:

$ zipgrep gateway test.zip Document/docs/iplist

View information with the zipinfo command

The zipinfo command in Linux lists the files contained within a zip file along with their permissions, compression type, original size, date, and time stamp. To view information about a specific zip file, type zipinfo followed by the file name, as shown below:

$ zipinfo filename

The following command will display information about the zip file files1.zip:

$ zipinfo files1.zip

Split the file with the zipsplit command

Sometimes, the size of the zip file is too large that you are unable to upload it or send it as an attachment because of size restrictions. With the zipsplit command, you can split the zip files into smaller files that are easier to transfer. To split a zip file into smaller files, with size no longer than <size>, the syntax would be:

$ zipsplit –n <size> zip_file

The <size> is the maximum size for the split files.

For instance, the command below will split test.zip into smaller files with size no longer than 104857600 bytes (104 MB).

$ zipsplit -n 104857600 test.zip

Here is the output of the above command. The test.zip file is split into three files, which are sequentially named as test1.ziptest2.zip, and test3.zip, respectively.

If you run the ls command, you will see all the three split zip files, along with the original zip file.

Add or view comments in a zip file with zipnote

With the zipnote command, you can add, view, and edit the comments in your zip file. To view comments, use the following command:

$ zipnote zip_file

Replace the zip file with your actual zip file name.

If there are no comments, you will see the following default view:


To add comments, first, you will need to redirect the output of zipnote to the comments file. Use the following command to do so:

$ zipnote zip_file > comments

For instance, to add comments to files1.zip, the command would be:

$ zipnote files1.zip > comments

Now, edit the comments file using the following command:

$ sudo nano comments

For each file, add your comments above the lines that say @ (comment above this line),then save and exit the file. We have added two comments in the comments file, as seen highlighted in the screenshot below.


Now write the comments to your zip file with the following command:

$ zipnote -w zip_file < comments

In our case, the command would be;

$ zipnote -w files1.zip < comments

Now, you can verify if the comments have been added by issuing the following command in Terminal:

$ zipnote zip_file

View help

To view help regarding zip command, use the following command:

$ zip --help

You can also visit the zip utility man page using the following command:

$ man zip

Unzip Command in Linux

With the unzip command, you can easily extract content from a zip file. To unzip a file, use the following syntax:

$ unzip options zip_file

Unzip single zip files

To unzip a single zip file, let’s say test.zip, the command would be:

$ unzip test.zip

It will unzip the file in the current directory.

Unzip a file to a different directory

You can also unzip a file to some other directory rather than the current directory using the -d option as follows:

$ unzip zip_file -d /path/to/directory

To unzip a zip file, test.zip to Documents, directory, the command would be:

$ unzip test.zip -d Documents/

Unzip multiple files

Consider there are multiple zip files in a current directory that you want to unzip. You can unzip all of them using a single command as follows:

$ unzip*.zip’

This command will unzip all the zip files residing in your current directory.

Suppress output when using unzip

Similar to the zip command, you can also hide the output of the unzip command using the -q option as follows:

$ unzip -q zip_file

Exclude files using unzip

If you want to unzip a zip file but do not want to extract a specific file, use the -x option below:

$ unzip zip_file –x filename

For instance, we have a zip filetest.zip containing three files within it. The following command will unzip all files except the one file report.txt:

$ unzip test.zip -x report.txt

Unzip password-protected zip files

To unzip a password-protected zip file without prompting, use -P option, followed by the password for the file:

$ unzip -P <password> zip_file

For instance, we have a zip file, test.zip, that is protected by the password “tin”. To extract this file, the command would be:

$ unzip -P tin test.zip

Overwriting zip files

If you are unzipping a file to a location where the extracted files already existed, then you will be prompted to: overwrite the current file, skip unzipping of the current file, overwrite all files, skip unzipping of all files, or rename the file.


To overwrite all existing files without prompting, use the -o option as follows:

$ unzip -o zip_file

List the content of a zip

Using the -l option with the unzip command, you can list the content of a zip file without extracting it.

$ unzip -l zip_file

Example:

$ unzip -l test.zip

The following is the output of the above command that lists the files contained within the zip file test.zip, along with their names, original file size, date, and timestamps.

View verbose information

In order to view verbose information without extracting the zip file, use the -v option as follows:

$ unzip -v zip_file

Example:

$ unzip -v test.zip

The following is the output of the above command that lists the files contained within the test.zip, along with their names, original file size, compressed size, compression method, compression ratio, date, and timestamps.

Checking for errors in an archive

With the -t option in the unzip command, you can check whether a zip file is valid and does not contain any errors.

$ unzip -t test1.zip

Example:

$ unzip -t test1.zip

The above command check for errors in the test1.zip file and displays results. The following output shows there is no error in the compressed file.

View help

To view help regarding the unzip command, use the following command:

$ unzip --help

You can also visit the unzip utility man page using the following command:

$ man unzip

Conclusion

That is all you need to know to master zip and unzip commands in Linux. In this article, we have discussed in detail the use of zip and unzip commands in Linux along with various command-line options and examples.

]]>
How to Set ulimit Value Permanently https://linuxhint.com/permanently_set_ulimit_value/ Sun, 08 Nov 2020 05:07:53 +0000 https://linuxhint.com/?p=76049

In Linux, ulimit is a built-in tool to manage resource allocation at global, group, and user levels. For a multi-user system like Linux, such a feature is almost paramount to have. It can prevent the consumption of unwanted system resources like RAM, and CPU power.

Check out how to set ulimit value permanently on Linux.

Ulimit value

Ulimit enforces the predefined limit of how much resources a user can use. The tool uses a certain configuration file as the core to assign the ulimit values. For more fine-tuned control, it’s better to edit the file.

$ cat /etc/security/limits.conf


There are two types of limits that can be imposed: soft and hard limits. It’s better to explain these types with a simple example.

Let’s say a system admin would like a certain user to hover around a certain value. Here, the user can exceed the value if necessary but not hard-bound by it. In this case, it’ll be a soft limit. On the other hand, if the admin wants to strictly impose the limit, then it’ll be a hard limit.

Using ulimit

Ulimit is a command-line tool. Here’s the basic structure of the ulimit command.

$ ulimit <options>

Display all limits

The “-a” flag will list all the options and configurations for a particular user. If no user is defined, it’ll print the limits for the current user instead.

$ ulimit -a

$ ulimit -a <username>


To display the soft limits of a user, use the “-S” flag.

$ ulimit -Sa <username>


To display the hard limits of a user, use the “-H” flag.

$ ulimit -Ha <username>


It’s possible to see the limits of a certain process. The details are located in the following file. Note that it’s a unique file for each of the processes that are currently running. Swap the PID field with the PID of the target process.

$ cat /proc/<PID>/limits

Limit parameters

To change the ulimit, you have to declare which type of limit you’d like to define. Here’s a shortlist with all the available parameters you can change. Almost all of them define the maximum value of each of the parameters.

  • b: Socket buffer size
  • c: Size of core files created
  • d: Process’s data segment size
  • e: Scheduling priority (“nice” value)
  • f: Number of files created by the shell
  • i: Number of pending signals
  • l: Size to lock into memory
  • m: Resident set size
  • n: Number of open file descriptors
  • p: Pipe buffer size
  • q: Number of bytes in POSIX message queues
  • r: Real-time scheduling priority
  • s: Stack size
  • t: CPU time (in seconds)
  • T: Number of threads
  • u: Number of processes available to a user
  • v: Amount of virtual memory available to process
  • x: Number of file locks

Change ulimit value temporarily

It’s possible to temporarily change the value of ulimit for a particular user. The change will remain effective until the user is logged out, the session expires or the system reboots. Here, I’ll be showing an example of how to set the max process number for a user.

To change the number of available processes to 12345, run the following command. It’ll impose a temporary hard limit on the user.

$ ulimit -u

$ ulimit -u 12345


Check out the hard limit to verify.

$ ulimit -Hu

Change ulimit value permanently

As mentioned earlier, ulimit utilizes a system configuration file that determines the default ulimit value. By making changes to this file, you can permanently change the ulimit value for any user.

Open the file in your favorite text editor. Note that the file has to be opened with root permission for the changes to be saved.

$ sudo vim /etc/security/limits.conf


Here, the entries of the file follow the following structure.

$ <domain> <type> <item> <value>

Let’s have a quick breakdown of each of the fields.

  • domain: Usernames, groups, GUID ranges, etc.
  • type: Type of limit (soft/hard)
  • item: The resource that’s going to be limited, for example, core size, nproc, file size, etc.
  • value: The limit value

Here’s a shortlist of all the available items.

  • core: Limits core file size (in KB)
  • cpu: CPU time (in min)
  • data: Data size (in KB)
  • fsize: File size (in KB)
  • locks: File locks user can hold
  • memlock: Locked-in-memory address space (in KB)
  • nproc: Number of processors
  • rtpio: Real-time priority
  • sigpending: Number of signals pending

For a full list of available items, check out the man page of limits.conf.

$ man limits.conf


For example, the following entry would limit the number of CPU cores the user “Viktor” can use down to 2.

$ viktor hard nproc 2

Once edited, save the file. To take the changes into effect, the affected user(s) need to log out and re-login. Depending on how it’s implemented, it may also require the system to reboot.

Final thoughts

The ulimit tool offers a powerful way of managing resources. It’s simple yet powerful in what it does. Whatever you do, make sure that the limit you’re about to implement is entered correctly. If you’re trying these things out for the first time, then try to test them out in a virtual machine first.

There’s more to the ulimit command than what I’ve discussed here. If you want to learn more, check out Linux ulimit command.

Happy computing!

]]>
An Introduction to Linux’s dmesg Command https://linuxhint.com/dmesg_tutorial/ Fri, 30 Oct 2020 22:14:10 +0000 https://linuxhint.com/?p=74871 Every operating system, including Linux, performs some activities silently without notifying the user. Although the user is unaware of these activities, it may be necessary to check these activities to identify operating system issues and the devices attached to the computer system.

Luckily, for the Linux operating system, all these activities are logged in the ring buffer, which can be accessed by using the diagnostic messages (or dmesg) command. The dmesg command in Linux can be used to display all the messages related to the events taking place within your operating system. This article will teach you how to use this helpful command in Linux.

Note: For this tutorial, we used Linux Mint 20

Command Usage

We will explain the usage of the diagnostic messages command by discussing a few examples.

Example #1: Viewing all Diagnostic Messages

We can view all types of diagnostic messages at once by performing these steps.

First, we need to click the shortcut icon of the Linux Mint 20 terminal to launch it.

You can see the newly launched terminal in the image below:

Now we will simply run the following command in the terminal:

Running this command will display a long list of diagnostic messages on your terminal. You can scroll down to see all the messages, as shown in the image below:

Example #2: Viewing Diagnostic Messages Page by Page

In the previous example, the list of diagnostic messages was very long and impractical to read. Therefore, you might want to view these messages page by page. which can be done by using the less command in Linux. In the command shown below, we are piping the output of the dmesg command to the less command so that diagnostic messages are displayed page by page.

You can see the output of the modified dmesg command in the image below.

Once you have read through the first page, you can press the spacebar to move to the next page, and so on, until the last page is reached, as indicated by the END keyword in the following image:

Example #3: Viewing Diagnostic Messages with a Specific Severity Level

The severity levels of diagnostic messages vary depending on the purpose they serve. For example, some messages convey general information, while others contain warnings. You can choose to view all the diagnostic messages of a specified severity level as follows:

First, run the command dmesg –level=LEVEL in your Linux Mint 20 terminal. Here, you need to replace LEVEL with a valid level (e.g., err, warn, info, notice). In our example, because we want to view all diagnostic messages of the error level, we replaced LEVEL with err.

This command will return all the diagnostic messages that have the error level, as shown in the following image:

Example #4: Viewing the Linux Version with dmesg Command

When we ran the dmesg command without any other parameters, the output was too large to view at once. Along with all the other information, the version of your Linux system was also displayed in that output, but it was difficult to locate. If you wish to see your Linux version with the dmesg command, then you can run the following command in your terminal:

Running this command will display the Linux version on your terminal as shown in the image below:

Example #5: Viewing Diagnostic Messages with Timestamps

An event occurs on an operating system at a certain time. For logging and auditing tasks, it is important to look at the timestamps of the events that take place within your operating system so that you can figure out when a problem occurred. To view the timestamps of the diagnostic messages, you can run the command below in your terminal:

The output in the following image shows the exact timestamps, including the day, date, and time, before each diagnostic message.

Example #6: Viewing the Diagnostic Messages related to a Specific Device

The diagnostic messages displayed by running the dmesg command alone are not specific to any device; instead, the messages related to all devices are displayed at once. However, you might want to view the diagnostic messages for a particular device to determine the issues related to that device only.

The dmesg command allows you to do so by running the command dmesg | grep –i “DEVICE”. Here, you have to replace DEVICE with the name of the device whose diagnostic messages you want to view. In our case, we want to check the diagnostic messages of the mouse. Therefore, we have replaced DEVICE with Mouse.

When you will run this command, all the diagnostic messages related to the mouse will be displayed on your terminal, as shown in the following image. You can view the diagnostic messages of any I/O device in the same manner.

Example #7: Viewing Diagnostic Messages with their Severity Levels

We viewed the diagnostic messages of a particular severity level in Example #3. However, if we want to display all the diagnostic messages with their severity levels, then we can run the command dmesg –x. The -x flag can be used with the dmesg command to display the diagnostic messages with their severity levels.

You can see from the following output that the severity level of a diagnostic message appears at the beginning of the message.

Example #8: Clearing the Diagnostic Messages History

Thousands of events take place in the operating system that renders your OS, and these events generate a long list of diagnostic messages, as shown in Example #1. However, the Linux system also provides a way to clear this log.

To clear your diagnostic messages history, you can run the command sudo dmesg –C. To clear the diagnostic messages history, which is important for auditing purposes, you need to run the dmesg command with sudo privileges. Otherwise, you will not be allowed to perform this operation. Moreover, the -C flag, coupled with the dmesg command, is responsible for clearing the dmesg log.

Once you will run this command, nothing will be displayed on your terminal. Therefore, to verify that the diagnostic messages history has been cleared, we will run the dmesg command again. This time, the dmesg command will not return any diagnostic messages on your terminal because the history has been erased.

Conclusion

This tutorial introduces the diagnostic messages generated by the Linux operating system and shows you how to view the timestamps of the events that occurred on the operating system, how to record all events of a specified severity level, and how to view the diagnostic messages related to a specific device. More advanced variations of the dmesg command shared in this article can be produced to obtain different results.

]]>
How to clear command history in Linux https://linuxhint.com/clear_command_history_linux/ Sun, 25 Oct 2020 05:34:21 +0000 https://linuxhint.com/?p=73268 The bash history stores the records of all terminal commands which are executed by a user on the command-line Linux system. Using the history feature, you can easily locate the previously executed commands on your Linux system through the arrow keys navigation.

Why should we remove the Linux Command line History?

Most of the time, we don’t want to reveal the terminal history of other users on your Linux system. For example, if you are giving classes to your students on a Lab computer and you might have taught some harmful commands and are not recommended to use on our system. But most of the students don’t have an idea about the side effects of these critical commands. A curious student may search about the command-line history and test them to check the working of each command. It may crash your system many times. However, you can repair or re-install your system in a quick way. But, it is not a good practice. So, in this case, we want to prefer to clear the command line history after working on it. Especially when you have shared access with your friends or colleagues. We have just elaborated it with just a simple example; there could be other problems through which you want to clear the Linux command line history. In this article, we will give you a demo of how you can clear the command line history in the Linux system.

We have executed all the commands on Ubuntu 20.04 terminal application in this article. Therefore, it is necessary to open the terminal window on your system. Click on the ‘Activities’ located at the left corner on your system’s desktop, and then using the application search bar, you will search the ‘terminal’ keyword. After completing the search, click on the terminal icon and launch it.

Removing the Linux Command line history

If you want to view the history of your terminal command then, type the following command on the terminal:

$ history

Normally, the command line history stores in a file named ‘bash_history’. This file you may locate in a particular user’s home directory /home/username/.bash_history. Execute the below-given command to locate the bash_history file:

$ ls -l /home/kbuzdar/.bash_history

Note: A root user can observe the command history of all user’s on your system. But, the standard user can only view their own command line history.

Remove a Line from the bash history

If you want to remove just a single line from the bash history file, then you can use the -d option with history command and enter the targeted line number, which you want to remove.

For example, we want to clear a command that contains your password where you have entered a password in a plain text; you can easily find the line number in the history file and clear it by executing the following command:

$ history -d 355

Remove or Clear all commands from the bash history

You can also clear or delete all entries from the bash history file. So, use the option -c with the history command. You can run the following command on the terminal to clear or delete the all bash history:

$ history -c

Alternatively, by running the following command, you can remove or delete all history of last executed commands in the bash history file permanently.

$ cat /dev/null > ~/.bash_history

Conclusion

In this article, we have presented a better understanding of the history command and why we need to clear it. From the above all mentioned command, I hope now can clear the history of your system easily. But, always remember that what you perform on the terminal all commands recorded in a bash history file, so it is recommended that you never use passwords in a plain-text format on the Linux command line. If you have any queries and thoughts related to this article then, please share your ideas with us.

]]>
How to find Linux distribution name and Version? https://linuxhint.com/find_linux_distribution_name_version/ Thu, 22 Oct 2020 08:44:56 +0000 https://linuxhint.com/?p=72695 While you are working on new Linux distribution, you might not know which Linux version is installed on your system. Sometimes, you need to meet a few system requirements while running an application on your system. However, different ways are available to check the Version of installed Linux distribution. Linux Mint 20 is the most growing Linux distribution and has a number of available graphical user interfaces that may vary from one user to the other. Hence, each user may also have a different running procedure. For this purpose, the recommended solution is to access and open the terminal command-line application.

In this article, we will learn how to check the installed Linux distribution name and Version on Linux Mint 20.

So, let’s start the demo.

Pre-requisites

You must have ‘sudo’ privileges or log in from the root user account on your system.

Check name and Version on Linux Mint 20

You can check the name and installed Linux distribution version using the following two different ways:

  • Check name and Version in Linux Mint 20 through the command line
  • Check Version using a graphical user interface method in Linux Mint 20

Let’s discuss each method one by one in detail.

Method 1: Check name and Version in Linux Mint 20 through the command line

Some users prefer to use the command line instead of the graphical user interface in Linux systems. Hence, using the command line, you have more options to get details about the installed Linux Mint distribution. To check the name and version of the Linux system on Linux Mint 20 environment, you need to follow the following different steps:

To open the terminal application, just log in to your Linux Mint 20 system and then click on the terminal icon that will be displayed on the taskbar.

Or you can pick the terminal by accessing the main menu. You can see the below-given screenshot, which is highlighted red:

In Linux distribution, specifically for Linux Mint 20, there are a lot of various utilities and text files present, which may help you to find the Linux Mint version. You can search the file that contains more information about the installed Linux Mint version, and that is available for all Debian based Linux/GNU distributions. This file you can find at etc/issue. Run the below-mentioned command on the terminal that will display the installed Linux Mint version:

$ cat /etc/issue

After executing the above command, the following output will show on the terminal:

Display installed Version Using hostnamectl utility:

The most common utility or command that is available for almost all Linux systems is ‘hostnamectl.’ It displays detailed information about the currently running operating system. To display the installed version of Linux distribution using ‘hostnamectl’ utility, follow the appended method:

Type the following command on the terminal to display the information about the installed Linux Mint version:

$ hostnamectl

The above command will display the complete information about the currently used operating environment and loaded kernel version. The following details about the installed Linux system to be displayed on the terminal:

The one, more file option ‘/etc/linuxmint/info,’ is available on the Linux Mint 20 distribution that keeps the details about the kernel and installed Version. Execute the following command on the terminal to view the kernel details:

$ cat /etc/linuxmint/info

The following output should display on the terminal window:

One more popular command which is available on Linux Mint is the ‘lsb_release’ command that provides much flexibility to select which piece of information is important for you to include in the Version checking task. To reveal the information about the released Version, distributor details, and codename, then you need to execute the following command:

$ lsb_release -crid

After executing the above command, you will achieve the following information on the terminal window:

Type the following command to view the information about Linux Mint:

$ /etc/lsb-release

The following installed distribution details will display on the terminal screen:

Or you can also execute the following command to check the installed version of Linux Mint on your system:

$ /etc/os-release

You will see the following detailed information about the Linux Mint version:

Method 2: Check version using the graphical user interface method in Linux Mint 20

As we have discussed above, various Desktop environment managers are available for all Linux Mint distributions. So, you need to follow the following steps to check the installed Linux Mint version for Cinnamon Desktop.

  • Click on the start menu, the following application list menu will display on the system.
  • Click on the ‘system settings’ icon from the list, which is also highlighted in the below-given screenshot.

  • Once you click on the system settings, the following window will display your system where you will see the different management applications. Scroll the mouse cursor on the displayed window and click on the ‘system info’ icon as follows:

The following window will display on your system:

From the above screenshot, you can get the details about the currently installed operating system, cinnamon version, Linux kernel, and other system resources like processor, memory, hard drive, and graphics card.

Conclusion

From the above article, we have learned how to check the details about the name and installed Version of Linux Mint. You can get detailed information about your system by following this tutorial. From all the information, as mentioned above, I hope now you can find the installed Version of any Linux distribution. We have discussed two different ways, i.e., by using a command line and by using a graphical user interface, through which a user can display the information about the installed Linux distribution. If you feel any difficulty related to the ways as mentioned above, then let us know via your feedback through the comments. We will welcome your queries.

]]>
How to use LSOF command in Linux https://linuxhint.com/use_lsof_command_linux/ Thu, 22 Oct 2020 03:53:50 +0000 https://linuxhint.com/?p=72640 In the Linux environment, everything is considered as a file and managed in folders or directories. So, while working on the Linux operating system, there might be numbers of folders and files that are being utilized; some of them would be visible for users, and others may be hidden. So, file management is very important in Linux/Unix distributions.

In the Linux system, the most popular command is LSOF, abbreviated for List Of Open File. This command shows the information about the files opened on your system. In other simple words, we can explain that the LSOF command provides information about the files that are opened by which process. It simply lists down the open files on the output console. It lists directory, shared library, block special file, regular pipe, an internet socket, character special file, Unix domain socket, and more others. Lsof command can be used to combine with the grep command to do more advanced features for listing and searching.

This article will give you a basic understanding of the LSOF command. Moreover, you will explore how to use this command in the Linux environment.

Pre-requisites

You must be login as a root user on your system or must have sudo command privillages.

We have performed all task on Ubuntu 20.04 system, which is mentioned below:

List open files using LSOF command

You can list all opened files with a complete description using the LSOF command.

# lsof


For example, here we have listed some open files for your better understanding. In the below screenshot, you will see the information in the form of columns like Command, PID, USER, FD, TYPE, etc.

Let’s explain each term one by one. In the first column, you will see Command is used for the command name. PID shows the process id. Under the column named USER, you will see the user role type or name. The above-displayed values in the image are self-explanatory. However, we will review the TYPE and FD columns.

FD is used for a File descriptor that has some values as:

  • cwd – Represents the current working directory.
  • rtd – Shows the root directory
  • txt – Used for program code and text data
  • mem – Used for memory-mapped file
  • 1u – file descriptor u for read and write mode, w for write mode, and r used for reading mode.

The TYPE column contains all files and identifications using keywords. DIR means directory. REG represents the regular file. CHR is used for character special files. FIFO means First In First Out.

List User-specific files using LSOF command

For example, if we want to list all opened files of user name kbuzdar then, using the following command, you can do this:

$ sudo lsof -u kbuzdar

Search processes working on a specific port

You can search those files or processes those running on a specific port number. For this purpose, you just need to use the following command with -i option and enter a specific port number.

# lsof -i TCP:22

If you want to list all open files running processes of TCP Port that ranges between 1-1024 then, execute the below-mentioned command:

# lsof -i TCP:1-1024

Display open files Only for IPv4 & IPv6

For example, you want to show only IPv4 and IPv6 network files. Run the following command to open files for IPV4 on the terminal window:

# lsof -i 4

For IPV6, use the following command:

# lsof -i 6

Display files by excluding specific users

If you want to exclude a root user then, you can exclude a root user by using the ‘^’ character with the command which is shown in the below screenshot:

# lsof -i -u^root


You can exclude a specific user by using their name.

# lsof -i -u^kbuzdar

Display all network connections using lsof command

Type the following lsof command with option -i to display the list of all network connections:

# lsof -i

Search process by PID

In the following example only shows those files or processes whose PID is 2 [two].

# lsof -p 2

Kill particular user activities

Sometimes you may need specific user processes. In this case, by executing the following command, you can kill all the processes of the ‘kbuzdar’ user.

# kill -9 `lsof -t -u kbuzdar`

Conclusion

In this article, we have seen how to use the lsof command on the Linux system. We have implemented different examples for a better understanding of lsof command. It’s not possible to elaborate on all available options but, you may explore the man page of lsof command to get more about this command. Share with us your feedback via comments.

]]>
How to Use Sudo Command in Linux? https://linuxhint.com/sudo_command_linux/ Tue, 20 Oct 2020 15:03:57 +0000 https://linuxhint.com/?p=72451

Among the different concepts of an operating system, the most crucial one is access control, which specifies the level of access that is granted to each user of that operating system. The access control policies ensure that no user is allowed to perform those activities for which he has not been granted any privileges. The two most common types of users in any operating system are the root user (has administrative level privileges) and the guest user (only has a limited set of privileges).

At times, even a guest user needs to perform some tasks that require administrative privileges. Fortunately, Linux provides us with a way of doing this, i.e., by making use of the “sudo” keyword before a command. It is such a magical keyword that whichever command is followed by this keyword is allowed to run with the root privileges rather than its own limited privileges. Sudo stands for Super User DO. For today’s discussion, our aim is to explain to you the usage of the “sudo” command in Linux.

Note: We have used Linux Mint 20 for explaining the method of using the “sudo” command.

The method of using the “sudo” command in Linux Mint 20 will be demonstrated by the following three example scenarios:

Scenario # 1: Updating your System with the Sudo Command

Whenever you want to install any new program, application, package, or command in your Linux system, you are always advised to update your system’s cache before it. It is so because, at times, some existing packages might be unpatched, which can cause trouble for you while installing anything new on your system. You can execute the “update” command with the root user privileges. Therefore, for updating your system with the sudo command, you will have to do the steps mentioned below:

In the first step, launch the terminal in any Linux distribution (I am using Linux Mint 20); it can be done by clicking on the terminal icon present on the. You can visualize the Linux Mint 20 terminal in the following image:

Once you have launched the terminal, the next thing you need to do is to run the “update” command while making use of the “sudo” keyword before it as shown below:

$ sudo apt update

When you hit the Enter key, the “update” command will take a few seconds to complete its execution, depending upon the total number of packages to be updated. The more the broken or outdated packages or dependencies are, the more time it will consume to execute the “update” command. However, once its execution finishes, your terminal will manifest the following output on it:

Scenario # 2: Upgrading your System with the Sudo Command

Usually, after a system update, you are required to upgrade those packages, too, whose upgraded versions are available on the Internet. This process takes a little longer than running the simple “update” command because, after all, you are installing all the newer versions of the packages whose upgrades are available. Moreover, these upgrades also require additional space on your system. Again, for upgrading the packages on your system, you need to run the “upgrade” command with the “sudo” privileges, which can be done as follows:

In your Linux Mint 20 terminal, you are supposed to execute the following command:

$ sudo apt upgrade

Once you press the Enter key to run this command, you will be asked for confirmation regarding whether you actually want to upgrade your packages or not. This is done because Linux considers it mandatory for asking the user before installing any such package that occupies an additional space on his system as well as requires a sufficient amount of time. If you are sure to carry on with this process, you can simply convey this to your OS by typing in “Y” in your terminal and then pressing the Enter key as highlighted in the image shown below:

It will take some minutes for the “upgrade” command to complete its execution, which again depends on the exact number of packages that are to be upgraded. However, once all the packages have been upgraded, your terminal will display the following output on it:

Scenario # 3: Creating a Text File with the Sudo Command

For accessing most of the text editors in the Linux operating system, you require root user privileges. Similarly, for creating a text file with the nano editor, you have to do it while making use of the “sudo” keyword, and the whole process is explained in the steps mentioned below:

In the first step, you have to execute the following command:

$ sudo nano MyFile.txt

You can replace “MyFile.txt” with any name of your choice to your text file instead of naming it MyFile.txt. As in this case, we have named our text file as Sudo.txt.

Once you run this command, it will not only create a new empty text file with the specified name in your Home directory, but it will also open that file with the nano editor from where you can add any content of your choice to this file as shown in the following image:

After making all these changes, you need to save your file and exit from the nano editor simply by pressing Ctrl+ X. You can also verify if a text file has actually been created in your Home directory by running the “sudo” command or not simply by going to your Home directory. Here, you will be able to find your newly created text file, as shown in the image below:

Conclusion

In this article, we tried to give you a brief overview of the usage of the “sudo” command in Linux Mint 20. These are just some of the example scenarios in which you can effectively make use of this command. However, this keyword can be used with a large number of other commands as well as on the other flavors of the Linux operating system.

]]>