Netstat Command Examples in Linux

Netstat Command Examples in Linux

The netstat is one of the most popular utilities to monitor connections over your network.

It allows you to easily monitor incoming and outgoing connections, listening ports, statistics, and more.

In this tutorial, I will show you some of the most examples of the netstat command on Linux.

1. Find all the listening ports

To find all the ports (TCP and UDP), you will have to append the -l flag with the netstat command:

netstat -l
Netstat Command Examples in Linux

2. List listening and non-listening ports

If you want to get a list of available sockets on your system, you can use the -a flag with the netstat command:

netstat -a
Netstat Command Examples in Linux

Now, let’s get to more specific ones.

3. Find TCP listening ports

If you want to list ports using TCP protocol and in the listening state, you will have to use -l flag for listening and -t flag for TCP connections:

netstat -lt
Netstat Command Examples in Linux

4. Find UDP listening ports

To list every listening UDP port on your system, you will have to append -l and -u flag with the netstat command:

netstat -lu
Netstat Command Examples in Linux

5. List all TCP port connections

If you want to list every socket using a TCP connection including listening and non-listening, use the -at flag with the netstat command:

netstat -at
Netstat Command Examples in Linux

Want to know the difference between listening and an established state?

  • LISTENING means it is listening for incoming connections.
  • ESTABLISHED indicates that the socket has an established connection.

6. List all UDP connections

If you want to list every socket utilizing the UDP, you can use the combination of -a and -u flag:

netstat -au
Netstat Command Examples in Linux

7. Get a statistical summary of each protocol

This is one of the handiest features of netstat which allows you to find the number of connections established, the number of messages sent and received, and a lot more.

To get a summary of each protocol, all you need to do is append the -s flag:

netstat -s
Netstat Command Examples in Linux

But what if you want statistics on specific protocols? Here’s how you do it.

8. Get statistics for a specific connection

Let’s start with the TCP.

To get the statistics of TCP connections, all you need to do is use the -s and -t flag with the netstat command:

netstat -st
Netstat Command Examples in Linux

Similarly, if you want the same for UDP, you will have to use the -su flag:

netstat -su
Netstat Command Examples in Linux

9. Get raw network statistics

If you are looking for raw data rather than filtered one, it can easily be produced using the -s (for statistics) and --raw (for raw):

netstat -s --raw
Netstat Command Examples in Linux

10. Find services with PID

If you are into troubleshooting, getting the PID of the service can be very handy. To get PID, all you need to do is use the -p flag:

sudo netstat -p
Netstat Command Examples in Linux

11. Find a specific listening service on the network

To find a specific listening, you can use the grep command which makes a killer combination while troubleshooting.

So let’s suppose, I want to look for an HTTPS service on listening state which can be done through the following command:

sudo netstat -apl | grep -w https
Netstat Command Examples in Linux

Want to know how to get more out of grep? you can refer to our detailed guide on that topic:

Explained: What is Grep Command in Linux?
Grep is perhaps one of the most used commands in Linux. Learn why it was created and how it s used in this explainer article.
Netstat Command Examples in Linux

12. Show transactions of network interfaces

The netstat utility can also be used to list available network interfaces and to get transactions of each one.

For that, all you need to do is append the -i flag to the netstat:

netstat -i
Netstat Command Examples in Linux

13. Monitor the network continuously using the netstat command

If you want to monitor the network continuously, you can do it with -c the option:

netstat -c
Netstat Command Examples in Linux

You can use appropriate flags such as -lt with -c and it will look for listening TCP connections continuously:

netstat -ltc
Netstat Command Examples in Linux

Pretty handy. Right?

More on Networking in Linux

If you have just started your carries or studies on networking, we have a detailed guide on most basic networking commands:

21 Basic Linux Networking Commands You Should Know
It’s not every day at It’s FOSS that we talk about the “command line side” of Linux. But as some of you readers pointed out in the internal survey (exclusive for It’s FOSS newsletter subscribers), you would also like to learn some command line tricks. So I
Netstat Command Examples in Linux

Want to know more about ports? We got you covered on that too:

Common Networking Port Numbers in Linux
Here are the common networking ports you’ll encounter in Linux.
Netstat Command Examples in Linux

That was it from my side. And if you have any doubts or have tips for beginners, you can share your precious knowledge through the comments.

Using gunzip Command in Linux

Using gunzip Command in Linux

Got a .gz file? It is a gzip-compressed archive file. Gzip reduces the file size better than the simple zip archive.

Now, to unzip a file, you have the unzip command in Linux. But you cannot use it on the gzip files.

To extract a .gz file, you need gunzip command.

It has a basic syntax:

gunzip <options> filename

Where,

  • options are used to tweak the default behavior of the utility.
  • filename is where you append the file for decompression.

Let me share some examples of using gunzip on Linux.

Decompress files using gunzip on Linux

To decompress a file, all you need to do is append the filename to the gunzip command:

gunzip compressed_file

For reference, here I want to decompress a Debian ISO file, so I will be using the following command:

gunzip debian-testing-amd64-DVD-1.iso.gz
Using gunzip Command in Linux

But if you notice carefully, it replaces the original file so what if you want to have both?

Decompress files while keeping the original intact

To keep the compressed file while using the gunzip command, you will have to use the -k option:

gunzip -k compressed_file
Using gunzip Command in Linux

And as you can clearly see, the original compressed file is as it is in addition to the decompressed file I got here.

Unzip files recursively

Imagine that your gzipped file has other gzipped files inside it. By default, the extracted file will have zipped folders inside it.

So if you want to decompress files recursively, you can specify the directory to the gunzip command with the -r option:

gunzip -r directory_name 

For example, Here I want to decompress every compressed file available inside the compressed directory so I will be using the following:

gunzip -rv compressed/
Using gunzip Command in Linux

And if you are curious, the additional -v option was used to have verbose output.

Force decompression

While decompression, if you have the file with the same name, it will ask you whether you want to override it or not:

Using gunzip Command in Linux

And if you want to skip that warning, you can use the -f option to proceed for forceful decompression:

gunzip -f compressed_file
Using gunzip Command in Linux

As you can see, when I used the -f option, it skipped the question part. A good solution if you are writing a script!

But wait! What about the unzip command?

Well, we have already covered how you can use unzip command with practical examples:

Unzip command in Linux: 8 Practical Examples
Got a zip file in the terminal? Learn how to use the unzip command in Linux with these practical examples.
Using gunzip Command in Linux

What’s the difference between unzip and gunzip you may ask?

Well, in the most simple terms, the unzip command is used to extract files with .zip extensions.

Whereas the gunzip command is used to deal with archives ending with .gz, .tar, etc.

I hope you will find this guide helpful and if you have any queries, let me know in the comments.

Compare Two Directories in the Linux Command Line

Compare Two Directories in the Linux Command Line

How do you compare two files in Linux? You use the diff command.

But how do you compare two folders in Linux? You still use the diff command.

It is easier to visualize the difference between two directories using a GUI tool.

In this tutorial, I’ll share how you can use the diff command to compare directories. I will also discuss a GUI tool called Meld.

The tree command shows the structures of the two directories I use in the examples.

Compare Two Directories in the Linux Command Line

So let’s start this tutorial with the CLI method.

Use the diff command to compare directories in Linux

To use the diff command, you will have to follow a simple syntax:

diff -qr Directory-1 Directory-2

To find the differences, you will have to use the -q option which will report only when the difference is found.

diff -q LHB-1 LHB-2
Compare Two Directories in the Linux Command Line

But if you notice carefully, the diff command only looked on file level 1. By default, it won’t look for the files inside the subdirectory.

To perform the search including the subdirectory, you will have to use the -r flag:

diff -qr LHB-1 LHB-2
Compare Two Directories in the Linux Command Line

But what if you want to know the similar files too?

You can easily do that using the -s flag. So if you will use both flags -q and -s, it will show both identical and different files of directories:

diff -qrs LHB-1 LHB-2
Compare Two Directories in the Linux Command Line
💡
The diff command shows what files differ in the directories. To see the difference, you can run the diff command again on the files to see how their content differs.

Use GUI to compare directories in Linux

If you are not a terminal fan and want to compare the directories in the easiest way possible, use Meld.

Meld is a GUI tool that allows you to check and merge differences.

You’ll have to install it first. In Ubuntu/Debian, use:

sudo apt install meld

It is also available as a flatpak:

flatpak install flathub org.gnome.meld

If you haven’t configured flatpak on your system, check out our detailed guide on how to set up flatpak on various Linux distros.

Once you are done with the installation, open the Meld from your system menu and follow the three easy steps:

  1. Select the Directory comparison
  2. Choose directories to compare
  3. Click on the Compare button
Compare Two Directories in the Linux Command Line

Once you click on the compare button, it will show you matching and different files available in the selected directories:

Compare Two Directories in the Linux Command Line

The ones which are marked with stars are the exact match.

Whereas filenames highlighted with green are only available to that respective directory.

Looking for more tools to compare?

If you are looking for more tools to compare files with various features, we already have a dedicated guide for that:

Compare Files in Linux With These Tools
Whether you’re a programmer, creative professional, or someone who just wants to browse the web, there are times when you find yourself finding the differences between files. There are two main tools that you can use for comparing files in Linux: * diff: A command line utility that comes…
Compare Two Directories in the Linux Command Line

And if you have any queries related to this guide or want to suggest me what should I cover next, let me know in the comments.  

tree Command Examples in Linux

tree Command Examples in Linux

You are already familiar with the directory structure in Linux. It is like the roots of a tree.

And that’s exactly the concept of the tree command. It shows the contents of the current directory and its subdirectories in a tree like fashion.

tree Command Examples in Linux

Before showing the examples of the tree command, let me quickly discuss how to install it.

Install tree

The tree utility does not come pre-installed in most Linux distributions. But you can find it in the official repositories and easily install it.

For Debian/Ubuntu base:

sudo apt install tree

For RHEL base:

sudo yum install tree

For Arch-based distros:

sudo pacman -S tree

Once done, all you need to do is append the directory or directory path to the tree command and it will show file contents in a tree manner:

tree target_directory
tree Command Examples in Linux

But the tree command can do more than just listing files in Linux. Here are some handful examples.

List only directories

If you want to list only the directories at the specified location, you can use the -d option.

tree -d target_directory
tree Command Examples in Linux

List hidden files

By default, the tree command won’t list hidden files but this behavior can be altered by using the -a option.

tree -a target_directory

And here, I have compared how it differs when used alongside the default manner (without any options):

tree Command Examples in Linux

Include the path of files

If you want to get the path for each file, all you need to do is use the -f option and it gets you the path of every file:

tree -f directory
tree Command Examples in Linux

But what about getting the full path? Well, you just have to append the full path of a directory (from home to the target one) as shown:

tree -f /home/sagar/Directory

And it is lengthy. So let me share a neat way.

In this case, you can utilize the value  pwd that holds the value full path. So change the directory where you want to use the tree command.

And use the following command and it will get you the full path of every file present in that directory:

tree -f "$(pwd)"
tree Command Examples in Linux

List files and directories based on the level

So if the directory has hundreds of subdirectories and if you only want to list the first certain levels such as want to include the first one or two subdirectories, you can use this feature.

You can specify the levels by appending the level (in numbers) to the -L option:

tree -L Level

For example, here, I listed files that are at level 2:

tree -L 2
tree Command Examples in Linux

And you can see the difference where on the left side, it showed every file present whereas, on the right side (where I used level 2), it only brought the files & directories placed at level 2.

List files with permission

To attach file permissions with every file, all you need to do is append the -p option:

tree -p TargetDirectory

But to make it convenient, I would suggest pairing it with -h option for better readability.

For example, Here I went with listing every file present in the MUSIC directory:

tree -ph MUSIC
tree Command Examples in Linux

Get the file size of a directory using the tree command

The tree command can show you the size of each file and directory at a specified location and will also sum the size for you in the end.

For that, you will have to use --df option and I would recommend pairing it with the -h for better readability:

tree --df -h TargetDirectory
tree Command Examples in Linux

List files based on the last modification using the tree command

There are two ways of sorting files based on modification:

  • First modified
  • Last modified

Sort files based on first modification

To sort files based on modification, you will have to use the -c option and it will sort files that were modified the first by default.

And here, I will also be using the -D option to get the date and time of modification:

tree -cD TargetDirectory
tree Command Examples in Linux

Sort files based on the last modification

In this case, you will have to alter the default effect of the -c option which will list files based on the first modification.

Which can easily be altered when paired with the -r option which will reverse the effect of -c option:

tree -cDr TargetDirectory
tree Command Examples in Linux

And you have them sorted for you!

Wrapping up

You can see how easy it is to visualize a nested directory structure with the tree command.

Ever since I installed it first, it’s been an essential part of my Linux command arsenal. I hope you also start using it extensively.

Scan Ports With netcat Command in Linux

Scan Ports With netcat Command in Linux

Whether you want to use SSH on an alternate port or deploy a web application to a specific port, the first step will always be to check whether the port is being utilized.

The netcat utility is one of the preferred tools to troubleshoot networks and can also be used to scan ports.  

For example, If I want to check whether port number 22 is open on my local VM, I’ll use the netcat command like this:

nc -zvn 192.168.1.6 22
Scan Ports With netcat Command in Linux

And as you can see, port no 22 is open for connections. That was easy.

But wait, there’s more you can do with the netcat command.

Scanning ports with the netcat command

You need to install netcat command first as it doesn’t come preinstalled in many distributions.

For Debian/Ubuntu-based distros:

sudo apt install netcat

For Fedora and RHEL:

sudo dnf install nc 

Now, let’s start with scanning multiple ports.

Scan multiple ports using the netcat command

To scan multiple ports at once using the netcat, you’d need to follow the given command syntax:

nc -zvn <target> port1 port2 port3
Scan Ports With netcat Command in Linux

Here,

  • -z is used to instruct netcat to scan ports without establishing a connection.
  • -v produces more verbose output.
  • -n stops netcat to perform domain name resolution.

Scan ports within a specific range using the netcat command

Indeed, you can use the previous method to scan for multiple ports but what if you want to scan more than 50 or 100 ports? You can define the range.

For example, If I want to scan ports ranging from 1 to 100, this would be my command:

nc -vz -w3 google.com 1-100
sagar@LHB:~$ nc -vz -w3 google.com 1-100
nc: connect to google.com (142.250.183.110) port 1 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 1 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 2 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 2 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 3 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 3 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 4 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 4 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 5 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 5 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 6 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 6 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 7 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 7 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 8 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 8 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 9 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 9 (tcp) failed: Network is unreachable
nc: connect to google.com (142.250.183.110) port 10 (tcp) timed out: Operation now in progress
nc: connect to google.com (2404:6800:4009:823::200e) port 10 (tcp) failed: Network is unreachabl

Of course, it’s google, and you can’t expect to have them ports open for you. But you can use this for your server and might find open ports

Seems pretty long list of unavailable ports right? In this case, you can use the grep command to fetch only the open ports:

netcat -w1 -znv 192.168.1.6 1-100 2>&1 | grep succeeded
Scan Ports With netcat Command in Linux

Here,

  • -w1 will force the netcat command to wait for 1 second for each port.
  • 2&1 redirects standard error.

Common Networking Port Numbers in Linux
Here are the common networking ports you’ll encounter in Linux.
Scan Ports With netcat Command in Linux

Wrapping Up

This was a quick guide on scanning open ports using the netcat command. Since you have found the opened ones, perhaps you would like to know how to close those ports.

I hope this guide resolves any queries you previously had and if not, let me know in the comments.

traceroute Command Examples in Linux

traceroute Command Examples in Linux

The traceroute is similar to the ping command but offers more detailed output. It traces the route from the origin to the target system.

If you didn’t know, when you connect to a remote system, the data travels through several intermediate nodes (your router, your ISP’s router, etc.).

traceroute Command Examples in Linux

Traceroute is used by system admins and networking professionals to troubleshoot the network.

Install traceroute in Linux

The traceroute utility does not come pre-installed in most modern Linux distros.

If you are on an Ubuntu-based distro, the given command should get your job done:

sudo apt install traceroute

Similarly, if you are on Fedora, you can benefit from the given command:

sudo yum install traceroute

Now, let’s jump to the examples part.

Use the traceroute command in Linux

Let me start with the most basic one, where I will append the hostname to the traceroute command and it will show me the list of routers (with IP) it took to reach the destination:

traceroute google.com
traceroute Command Examples in Linux

It took 7 routers to reach the destination and by default, it sent 3 packages to each one and returned the time it took to respond.

There are more ways of using the tarecroute command in Linux. Let’s see the examples.

1. Configure wait time

The default wait time in traceroute is 3 seconds meaning it will wait for 5 seconds before jumping to the next one.

And if you want to change the defaults, you can append the number of seconds with the -w option:

For example, I changed the wait time to 1 second for google.com:

traceroute -w 1 google.com
traceroute Command Examples in Linux

2. Change the number of packages sent/received

By default, traceroute sends 3 packages for a hop and if you want to change this behavior, you will have to use -q option.

For reference, I will send 4 packets per hop over the google domain:

traceroute -q 4 google.com
traceroute Command Examples in Linux

3. Specify the maximum number of hops

The default maximum number of hops for a single query is 30 in traceroute which can be extended to 255.

For that, you can append the max number of hope with -m option:

traceroute -m 4 google.com
traceroute Command Examples in Linux

4. Specify with what TTL to start

By default, the traceroute will start with the first TTL but you can change this behavior using -f option.

For reference, I wanted to start tracerouting on google’s domain from the 5th TTL so had to use the given command:]

traceroute -f 5 google.com
traceroute Command Examples in Linux

5. Add alternate source IP address for tracerouting

If you want to add an alternate source along with what you generally add for tracerouting, you will need to append the alternate IP with -s option.

For example, I have added an alternate source IP 192.168.1.7 alongside google.com:

traceroute -s 192.168.1.7 google.com
traceroute Command Examples in Linux

6. Disable hostname mapping to IP address while tracerouting

If you want to disable hostname mapping while tracerouting for some reason, you can use the -n option:

traceroute -n google.com
traceroute Command Examples in Linux

7. Route packages through the gateway using traceroute

You can specify the gateway address using -g option alongside the domain you want to traceroute.

For example, I have added 192.168.1.7 as a gateway address:

traceroute -g 192.168.1.7 google.com
traceroute Command Examples in Linux

8. Change the destination port in traceroute

If you want to change the destination port of your source domain while tracerouting, you will have to use -p to specify the port.

For example, I have changed my destination port to 29879:

traceroute -p 29879 google.com
traceroute Command Examples in Linux

9. Set maximum packet length

By default, traceroute will use a packet length of 60 bytes and you can alter this behavior by just appending packet size to the source IP.

For example, I changed to 100 bytes of maximum packet length while tracerouting:

traceroute google.com 100
traceroute Command Examples in Linux

10. Disable probe packet fragmentation

If you don’t want to allow probe packet fragmentation, there is a straightforward way to stop it.

You just have to use -F and there will be no probe packet fragmentation:

traceroute -F google.com
traceroute Command Examples in Linux

Wrapping Up

If you are curious to know how the traceroute works, you can refer to the other guide where I’ve explained the working of the traceroute.

I hope you will find this helpful and if you have any queries, let me know in the comments.

Enable Timestamp in History Command in Linux

Enable Timestamp in History Command in Linux

You are familiar with the history command in Linux. It lets you see which commands you ran in the past.

But there is one issue. By default, the history command does not show when the command was executed (with date and time).

This could be helpful in some cases to know the time when a certain command was executed last.

And in this quick tip, I will show you how you can enable timestamps in the history command.

Enable timestamp in history command

To enable timestamps in the history command, you have to export the HISTTIMEFORMAT environment variable.

Use the export command like this:

export HISTTIMEFORMAT="%F %T "

Here,

  • %F will show the date in YYYY-MM-DD format.
  • %T will show time in HH:MM:SS format.

The modifications should now be reflected when you use the history command again:

Enable Timestamp in History Command in Linux
History now shows the timestamps of the commands

However, as the modifications are only effective during the current session, the history command will return to its previous appearance after a reboot.

And if you want to apply timestamp permanently, here’s how you do it.

Enable history timestamp permanently

To have a timestamp in the history command permanently, you’ll have to make changes in .bashrc file.

Yes, no surprises there. If you want to make an environment variable permanent, it goes in your bashrc.

Open the .bashrc file in your favorite text editor. I am using Nano here.

nano ~/.bashrc

You can use Alt + / to jump to the end of the file in Nano and add the following line:

export HISTTIMEFORMAT="%F %T "
Enable Timestamp in History Command in Linux

Save the changes and exit nano.

Now, to take those changes into effect, you will have to source the .bashrc file using the source command:

source ~/.bashrc

And now, whenever you will use the history command, it will show the timestamps with every command.

Wrapping Up

This was a quick tutorial on how you can enable timestamps in the history command. I hope you find this quick history command tip helpful in your Linux journey. Here are a few more.

5 Simple Bash History Tricks Every Linux User Should Know
Effectively using bash history will save you plenty of time in the Linux terminal.
Enable Timestamp in History Command in Linux

Do leave a comment if you have any doubts or suggestions.

How to Use the duf Command in Linux

How to Use the duf Command in Linux

The duf utility is nothing but an enhancement of what traditional du and df commands do to check used and free space in a structured and eye-pleasing way.

And this is how it shows utilized disk space by default:

How to Use the duf Command in Linux

Looks neat and pretty, right?

So in this tutorial, I will walk you through how to install and use the duf command in Linux.

Installing duf

If you are on Ubuntu 22.04 or Debian unstable, you can use the apt package manager for straightforward installation:

sudo apt install duf

And if you are on Arch, the pacman command would get the job done:

sudo pacman -S duf

But if you are on Debian stable or running an older version of Ubuntu, you can use pre-build deb packages to install duf:

wget https://github.com/muesli/duf/releases/download/v0.8.1/duf_0.8.1_linux_amd64.deb

Now you can install the deb package using the given command:

sudo apt install ./duf_0.8.1_linux_amd64.deb

You can access more pre-build packages including rpm from their release page.

Similarly, you can follow instructions from their homepage to build a package from the source.

Using duf to check disk usage and free space

You can simply use duf without any options and it will get you a list of mounted devices:

duf
How to Use the duf Command in Linux

List specific devices and mounting points

You can use duf to list one or more devices at the same time. You just have to specify the path of the mounting port or device and that’s it:

duf DriveName

For example, I went on listing home directory and my external drive:

duf /home /media/sagar/HDD
How to Use the duf Command in Linux

Filter drives and mounting points

The duf utility provides various options so that you can filter output and have intended results.

For instance, you can the --only option to show only specific devices:

duf --only device_name

So if I want to list the locally mounted devices, I will have to append local with the --only option:

duf --only local
How to Use the duf Command in Linux
💡
Similarly, you can use the --hide option to alter the effect.

And if you want to list specific filesystems, you can use --only-fs and append filesystem types.

For instance, I looked for tmpfs (temporary filesystem):

duf --only-fs tmpfs
How to Use the duf Command in Linux

Sort output

You can sort the output based on a variety of keys such as size, usage, and more using the --sort option.

For example, if I want to sort the output based on usage:

duf --sort usage
How to Use the duf Command in Linux

Get JSON output

If you are someone like me who prefers to have a JSON output, you can use --json option:

duf --json
How to Use the duf Command in Linux

And if you want to save the output in a text file, you can redirect the standard output to the text file:

duf --json > duf.json

Wrapping Up

Duf is one of the new CLI tools that is gaining quite some popularity among Linux users. And you can see how it does things better than the traditional df and du commands.

Here are some more modern, alternative Linux commands.

Modern Alternatives to Some of the Classic Linux Commands – It’s FOSS
Here are some faster, better and feature rich alternative command line tools to replace the decades old legacy Linux commands.
How to Use the duf Command in Linux

I hope the same goes for you too.

The Lesser Known Dir Command in Linux

The Lesser Known Dir Command in Linux

How do you see the contents of a folder in the Linux terminal? You use the ls command.

In fact, the ls command is so popular that many Linux users don’t even know about dir.

Yes, there exists a dir command with the sole purpose of showing you the directory contents. And in this tutorial, I’ll show you how to use it.

Using dir command to list directory contents

The basic syntax for the dir command is as follows:

dir [options] [Directory] [Files]

Where:

  • options: These are optional parameters that can be used to control the output of the dir command.
  • Directory: This is the directory whose contents need to be listed.
  • Files: This is a list of specific files that need to be listed.

The most basic use of the dir command is to list the contents of the current directory.

To do this, simply type dir without any options and press enter. If no directory is specified, the dir command will list the contents of the current working directory.

dir

The default behavior is to sort the output in alphabetical order.

The Lesser Known Dir Command in Linux
Default dir Command

Displaying Color Output

Unlike the ls command, the dir command doesn’t display output in colors by default. If you want, you can enable color output for the dir command by using the --color option.

dir --color

This option is useful when you want to identify certain files or folders based on their color quickly.

The Lesser Known Dir Command in Linux
dir Command with Colored Output

There are more colors available that are used to differentiate between different file types.

  • Green: Regular files
  • Blue: Directories
  • Cyan: Symbolic links
  • Red: Broken links
  • Yellow: Device files

Using Long Listing Format

You can use the -l option with the dir command to display output in a long listing format.

This displays information like permissions, ownership, timestamps, etc.

dir -l
The Lesser Known Dir Command in Linux
Long Listing Format

The dir command also supports other listing format options:

  • -1: list entries in a single column
  • -C: list entries in columns
  • -m: list entries in a comma-separated format
The Lesser Known Dir Command in Linux
Display Entries as Comma Separated

The -m option is especially useful when you want to quickly generate a list of files that other programs or scripts can use. Machine learning is an example of where this might be useful.

Listing Hidden Files

The files beginning with a dot (.) are hidden files in Linux and they are not displayed by default.

Similar to ls, you use the option -a (short for all) to list all the files including hidden ones:

dir -a
The Lesser Known Dir Command in Linux
Display Hidden Files

In the output above, you might notice that there are two special entries – . (current directory) and .. (parent directory). These are called pseudo-files.

If you don’t want to see these special entries in the output, you can use the -A option (short for almost-all).

dir -A
The Lesser Known Dir Command in Linux
Listing Without Special Entries

Displaying File Type Indicators

The -F option, short for “classify”, appends a character after each entry to indicate the type of file. This information can be very useful, especially when you want to identify certain types of files quickly.

dir -F
The Lesser Known Dir Command in Linux
File Type Indicators

As you can see in the screenshot above, the -F option appends a ‘/’ character after each directory. Other indicators are

  • – for directories
  • – @ for soft links
  • – * for executable files
  • – | for FIFO (named pipes)

There is a similar option called --file-type that does the same except showing * for executable files.

dir --file-type
The Lesser Known Dir Command in Linux
Displaying Extensions of Files

I like to use it for ignoring files of certain types from the display.

As you can see, all the files that start with “temp” and all the files that end with “.txt” are ignored.

The Lesser Known Dir Command in Linux
Ignoring Specified Entries

Displaying Output in Human Readable Format

The dir command also supports the -h option, short for “human-readable”.

If a file is of size 1024 bytes, it will be displayed as 1K. Similarly, if a file is of size 1048576 bytes, it will be displayed as 1M. This option uses 1000 as the base for file sizes, not 1024.

This can come in handy when you want to see the file sizes quickly.

You should use the -l option along with -h.

dir -h -l
The Lesser Known Dir Command in Linux
Listing in Human Readable Form

Displaying Files by Size

The dir command also supports the -S option to sort files by size. This can come in handy when you want to see which files are taking up the most space.

dir -S -l

As you can see in the screenshot below, the most space-consuming files are displayed on top.

The Lesser Known Dir Command in Linux
Displaying Files by Size

Conclusion

You might have realized that the dir command is no different than the ls command. ls is more popular and almost every Linux user knows about it. Since dir command doesn’t offer anything special, it doesn’t give reasons to ditch ls command.

Pretty Print JSON in Linux Command Line

Pretty Print JSON in Linux Command Line

While JSON files are preferred for storing data in human-readable form, it is good enough to give headaches when they are minified.

Of course, it will stay in human-readable form in any case but having a well-formatted file is always easy on the eyes. So let me share what you should expect from this guide first:

Pretty Print JSON in Linux Command Line

And throughout this guide, I’ll be using the following unstructured JSON file for relevance:

{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"},{"value": "Close", "onclick": "CloseDoc()"}]}}}

Now, let me share various ways of reading JSON files in a structured, human-readable format.

Method 1: Pretty print JSON files using the jq command

The jq is a command-line JSON processor that allows users to modify JSON files in various ways allowing users various options to re-format their JSON files.

But it requires to be installed first. If you’re on a Debian-based distro, you can use this command:

sudo apt install jq

And the most straightforward way of re-formatting your JSON files is appending the filename with .:

jq . File.json
Pretty Print JSON in Linux Command Line

And jq allows users to format their files in 2 ways:

  • --tab will add a tab for each indentation level instead of the default two spaces.
  • --indent number allows users to add spaces (up to 8) for each indentation level.

For example, I’ll be adding four spaces for each indentation:

jq . --indent 4 File.json
Pretty Print JSON in Linux Command Line

Method 2: Using json_pp to pretty print JSON files

The json_pp is a Perl module intended to convert the input to different output formats and can also be used to pretty print JSON files.

It needs to be piped with the cat command to work. Let me show you how:

cat File.json | json_pp
Pretty Print JSON in Linux Command Line

Method 3: Using Python to pretty print JSON file

Being an integral part of the majority of the system, what not to put Python to accomplish our desired task?

To format JSON files using Python, I’ll be using json.tool with the -m option:

python3 -m json.tool File.json
Pretty Print JSON in Linux Command Line

Method 4: Using the json_xs command to pretty print JSON file

This won’t show any results in STDIN but will make changes in the file itself. Making it the only method that saves changes directly in this entire guide.

For example, I’ll save the changes to a new file named Structured.json:

<File.json json_xs >Structured.json
Pretty Print JSON in Linux Command Line

Wrapping Up

This was my take on how you can print pretty JSON files in Linux by multiple methods. And if you want to have complete control over formatting, I’d suggest using the first method.

And if you still have any doubts, feel free to ask in the comments section.