Linux Commands – TecAdmin https://tecadmin.net How to guide for System Administrator's and Developers Mon, 16 Jan 2023 17:40:37 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 Sort Command in Linux with Practical Examples https://tecadmin.net/linux-sort-command/ https://tecadmin.net/linux-sort-command/#respond Mon, 16 Jan 2023 17:40:37 +0000 https://tecadmin.net/?p=33930 The `sort` command in Linux is part of the GNU Coreutils package. This command is used to sort lines of text in a specified file or from the standard input in an ascending/descending order. The sorted output can be written to a file or displayed on the standard output. The `sort` command is a simple [...]

The post Sort Command in Linux with Practical Examples appeared first on TecAdmin.

]]>
The `sort` command in Linux is part of the GNU Coreutils package. This command is used to sort lines of text in a specified file or from the standard input in an ascending/descending order. The sorted output can be written to a file or displayed on the standard output. The `sort` command is a simple and powerful tool that can be used in various scenarios, from sorting data in a file for further analysis to preparing data for a report.

In this article, we will discuss the various options available with the `sort` command and provide some practical examples to illustrate its usage.

The basic syntax of the `sort` command is as follows:

# Syntax
sort [options] [file(s)]

This command provides various options that can be used to customize the sorting process and file(s) that need to be sorted. If no file is specified, the `sort` command will sort the input from the standard input (i.e., the keyboard).

Here are some frequently used options with the `sort` command in Unix/Linux systems:

  • -r: sort the input in reverse order.
  • -n: sort the input numerically.
  • -k: sort the input based on a specific field or column.
  • -b: ignore the leading blanks.
  • -t: specify the field separator.
  • -u: remove duplicate lines from the output.
  • -o: specify the output file.

Let’s take a closer look at each of these options with some examples.

Sorting File Content

The default content is sorted in ascending order basis on the first character. You can simply type the `sort` command followed by the file name.

sort data.txt 

You can also use the following commands to provide input to the command.

sort < data.txt 
cat data.txt | sort 

Sorting in Reverse Order

The -r option is used to sort the input in reverse order. Here's an example of how to use this option:

sort -r data.txt 

This command sorts the lines of text in the data.txt file in reverse order and displays the result on the screen.

Numerical Sorting

The -n option is used to sort the input numerically. This option is useful when sorting numbers that are represented as text. Here's an example of how to use this option:

sort -n data.txt 

This command sorts the lines of text in the data.txt file numerically and displays the result on the screen.

Sorting by Field

The -k option is used to sort the input based on a specific field or column. This option is useful when sorting tabular data where each line represents a record and fields are separated by a specific delimiter. The field number is specified with the option, and the fields are numbered starting from 1. Here's an example of how to use this option:

sort -k 2 data.txt 

This command sorts the lines of text in the data.txt file based on the second field (column) and displays the result on the screen.

Specifying the Field Separator

The -t option is used to specify the field separator when sorting by field. By default, the `sort` command assumes that the fields are separated by a space or tab character. However, this option allows you to specify a different character as the field separator. Here's an example of how to use this option:

sort -t "," -k 2 data.txt 

This command sorts the lines of text in the data.txt file based on the second field (column) and the field separator is ','. It will display the result on the screen

Removing Duplicate Lines

The -u option is used to remove duplicate lines from the output of the `sort` command. This option is useful when sorting a large file and you only want to keep unique lines. Here's an example of how to use this option:

sort -u data.txt 

This command sort the lines of text in the data.txt file and remove any duplicate lines from the output. The result is displayed on the screen.

Specifying the Output File

The -o option is used to specify the output file for the sorted data. This option is useful when saving the sorted data to a different file rather than displaying it on the screen. Here's an example of how to use this option:

sort data.txt -o sorted_data.txt 

Instead of the option, you can also use the redirect ">" operator to write content to the file.

sort data.txt > sorted_data.txt 

This command sorts the lines of text in the data.txt file and saves the result to a new file called sorted_data.txt.

Combining Multiple Options

You can combine different options to achieve the desired sorting result. For example, to sort a file numerically in reverse order and save the result to a new file, you can use the following command:

sort -nr data.txt -o reverse_sorted_data.txt 

You can also combine different options like this,

sort -t "," -k 2,3 -u data.txt 

This command sorts the lines of text in the "data.txt" file based on the second and third field (column) and the field separator is ',' and removes duplicate entries from the result and displays it on the screen

Conclusion

In conclusion, the `sort` command is a powerful and versatile tool that can be used to sort data in various scenarios. The various options available with the `sort` command allows you to customize the sorting process and achieve the desired result. With the examples and explanations provided in this article, you should have a good understanding of how to use the `sort` command and be able to apply it to your own data.

The post Sort Command in Linux with Practical Examples appeared first on TecAdmin.

]]>
https://tecadmin.net/linux-sort-command/feed/ 0
Sed Command in Linux with 15 Practical Examples https://tecadmin.net/sed-command-in-linux-with-examples/ https://tecadmin.net/sed-command-in-linux-with-examples/#respond Fri, 13 Jan 2023 10:40:35 +0000 https://tecadmin.net/?p=33461 The `sed` command is an essential tool for manipulating text in Linux. It allows you to search for patterns in a text and perform various operations on the matching text, such as replacing it, deleting it, or printing it. This command takes input from a file or standard input. The default sed command doesn’t make [...]

The post Sed Command in Linux with 15 Practical Examples appeared first on TecAdmin.

]]>
The `sed` command is an essential tool for manipulating text in Linux. It allows you to search for patterns in a text and perform various operations on the matching text, such as replacing it, deleting it, or printing it. This command takes input from a file or standard input.

The default sed command doesn’t make changes to the original file until you used the -i command line parameter. The command alerts the text and sends the result to standard output. You can also redirect the text to the file as per the requirements.

In this article, we’ll provide 15 practical examples of using the `sed` command to perform various tasks.

Replace Strings Example using Sed

1. Replace string in a file

To replace a string in a file, you can use the 's/old_string/new_string/g' command. The syntax is:

# Syntax
sed 's/old_string/new_string/g' file_name

To replace strings in a file using the sed command, use the -i argument to make the changes in-place. The command string must include the substitute command ‘s’, the original string, and the replacement string. For example, to replace all instances of the string “apple” with the string “banana” in a file called fruits.txt, use the following command:

See the following example:

sed 's/apple/banana/g' fruits.txt 

This command reads the content from the “fruits.txt” file and replaces all occurrences of the word “apple” with the word “banana” and prints the resulting text to the terminal. The g tells the command to replace all matching occurrences globally in the file.

You can also make the changes in the same file with the -i option.

sed -i 's/apple/banana/g' fruits.txt 

You will see that the original file is modified. You can also make s backup of file before making changes in original file.

sed -i.bak 's/apple/banana/g' fruits.txt 

A backup file of the original will be created in current directory with name fruits.txt.bak.

2. Replace the first occurrence of each line

To substitute only the first occurrence of a pattern on each line, you can use the s/pattern/replacement/ command. For example, to replace only the first occurrence of the word “apple” with the word “banana” in the file fruits.txt, you can use the following command:

sed 's/apple/banana/' fruits.txt 

3. Replace the last occurrence of each line

To substitute only the last occurrence of a pattern on each line, you can use the s/pattern/replacement/g’ command. For example, to replace only the last occurrence of the word “apple” with the word “banana” in the file fruits.txt`, you can use the following command:

sed 's/\(.*\)apple/\1banana/g' fruits.txt 

4. Replace string at specific line number

To replace a string on a specific line, you can use the lineNumbers/pattern/replacement/ command. For example, to replace the first occurrence of the word “apple” with the word “banana” on line 3 of the file fruits.txt, you can use the following command:

sed '3s/apple/banana/' fruits.txt 

5. Replace string from range of line numbers

To replace a string on a range of lines, you can use the startLineNumber,endLineNumber/pattern/replacement/ command. For example, to replace the first occurrence of the word “apple” with the word “banana” on lines 3 through 5 of the file fruits.txt, you can use the following command:

sed '3,5s/apple/banana/' fruits.txt 

Deleting Lines in File using Sed

6. Delete first line from file

To delete a line that contains a certain string, you can use the /pattern/d command. For example, to delete all lines that contain the word “apple” in the file fruits.txt, you can use the following command:

sed '1d' fruits.txt 

7. Delete line contains certain string

To delete a line that contains a certain string, you can use the '/pattern/d' command. For example, to delete all lines that contain the word “apple” in the file fruits.txt, you can use the following command:

sed '/apple/d' fruits.txt 

8. Delete lines except the matching string

To invert the matching lines, you can use the `!` operator in combination with other commands. For example, to delete all lines that contain the word “apple” in the file fruits.txt, you can use the following command:

sed '/apple/!d' fruits.txt 

9. Delete the range of lines

To delete a range of lines, you can use the startLineNumber,endLineNumberd command. For example, to delete lines 3 through 5 of the file fruits.txt, you can use the following command:

sed '3,5d' fruits.txt 

10. Delete empty lines from file

You can remove the empty lines from the file using '/^$/d' option.

sed '/^$/d' fruits.txt 

This command consider a line as empty, that doesn’t contain any character, even a single space.

Printing Lines from File using Sed

11. Print line numbers only

To print only the line numbers of matching lines, you can use the '/pattern/=' command. For example, to print the line numbers of all lines that contain the word “apple” in the file fruits.txt, you can use the following command:

sed '/apple/=' fruits.txt 

12. Print the range of file

To print a range of lines, you can use the 'start,endp' commands. For example, to print the first 10 lines of the file fruits.txt, you can use the following command:

sed -n '1,10p' fruits.txt 

Inserting Lines to File using Sed

13. Insert a new line after matching pattern

To insert a line after a certain pattern, you can use the '/pattern/a\newline' command. For example, to insert the line “grapes” after the line that contains the word “apple” in the file fruits.txt, you can use the following command:

sed '/apple/a\grapes' fruits.txt 

14. Insert a new line before matching pattern

To insert a line before a certain pattern, you can use the '/pattern/i\newline' command. For example, to insert the line “grapes” before the line that contains the word “apple” in the file fruits.txt, you can use the following command:

sed '/apple/i\grapes' fruits.txt 

Other Tasks using Sed

15. Change Case of Characters

To change the case of a string, you can use the 'y/old/new/' command. For example, to change all lowercase letters to uppercase in the file fruits.txt, you can use the following command:

sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' fruits.txt 

Conclusion

We hope these examples have been helpful in showing you the versatility of the sed command. Remember that sed is a very powerful tool and it’s important to test your commands carefully before using them on important files. If you have any questions or need further assistance, don’t hesitate to ask. With these practical examples under your belt, you’ll be well on your way to mastering the sed command and becoming a proficient Linux administrator.

The post Sed Command in Linux with 15 Practical Examples appeared first on TecAdmin.

]]>
https://tecadmin.net/sed-command-in-linux-with-examples/feed/ 0
lsusb Command in Linux (Display USB device Details) https://tecadmin.net/lsusb-command-in-linux/ https://tecadmin.net/lsusb-command-in-linux/#respond Tue, 10 Jan 2023 07:12:55 +0000 https://tecadmin.net/?p=33880 The `lsusb` command is a utility in Linux that allows users to list the USB (Universal Serial Bus) devices connected to the system. This utility is the part of “usbutils” package, which provides utilities to display information about USB buses in the system and the devices connected to them. A USB (Universal Serial Bus) is [...]

The post lsusb Command in Linux (Display USB device Details) appeared first on TecAdmin.

]]>
The `lsusb` command is a utility in Linux that allows users to list the USB (Universal Serial Bus) devices connected to the system. This utility is the part of “usbutils” package, which provides utilities to display information about USB buses in the system and the devices connected to them.

A USB (Universal Serial Bus) is a widely used standard for connecting devices to computers. It allows users to connect a many of devices such as keyboards, mice, printers, and external storage devices to their computers with ease. The `lsusb` command can be used to display information about these devices, including their vendor and product ID, device name, device driver, and others.

In this article, we will discuss the syntax and options of the lsusb command, and provide examples of how to use it to list and display information about USB devices in Linux.

Syntax

The basic syntax of the lsusb command is:

lsusb [options]

Options

Some common options used with the lsusb command are:

  • -v: Display detailed information about the USB devices.
  • -t: Display a tree-like view of the USB devices.
  • -s: Display information about a specific USB device, specified by its bus and device number.
  • -d: Display information about a specific USB device, specified by its vendor and product ID.
  • -D: Selects which device will be examined.

Examples

  1. To list all the USB devices connected to the system, use the lsusb command without any options:
    lsusb 
    
    Output
    Bus 002 Device 004: ID 046d:0a37 Logitech, Inc. USB Headset H540 Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 004: ID 413c:301a Dell Computer Corp. Bus 001 Device 003: ID c0f4:05e0 Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
  2. To display detailed information about the USB devices, use the -v option:
    lsusb -v 
    
  3. To display a tree-like view of the USB devices, use the -t option:
    lsusb -t 
    
    Output
    /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M |__ Port 1: Dev 4, If 0, Class=Audio, Driver=snd-usb-audio, 12M |__ Port 1: Dev 4, If 1, Class=Audio, Driver=snd-usb-audio, 12M |__ Port 1: Dev 4, If 2, Class=Audio, Driver=snd-usb-audio, 12M |__ Port 1: Dev 4, If 3, Class=Human Interface Device, Driver=usbhid, 12M /: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/4p, 480M |__ Port 1: Dev 3, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M |__ Port 1: Dev 3, If 1, Class=Human Interface Device, Driver=usbhid, 1.5M |__ Port 2: Dev 4, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
  4. To display information about a specific USB device, use the -s option followed by the bus and device number. For example, to display information about the USB device on bus 2 and device 4, use the following command:
    lsusb -s 2:4 -v 
    
    Output
    Bus 002 Device 004: ID 046d:0a37 Logitech, Inc. USB Headset H540 Couldn't open device, some information will be missing Device Descriptor: bLength 18 bDescriptorType 1 bcdUSB 2.00 bDeviceClass 0 bDeviceSubClass 0 bDeviceProtocol 0 bMaxPacketSize0 64 idVendor 0x046d Logitech, Inc. idProduct 0x0a37 USB Headset H540 bcdDevice 1.22 iManufacturer 1 iProduct 2 iSerial 3 bNumConfigurations 1 Configuration Descriptor: bLength 9 bDescriptorType 2 wTotalLength 0x011c
  5. To display information about a specific USB device, use the -d option followed by the vendor and product ID. For example, to display information about a device with vendor ID 8087 and product ID c52b, use the following command:
    lsusb -d 1d6b:0002 -v 
    
    Output
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Couldn't open device, some information will be missing Device Descriptor: bLength 18 bDescriptorType 1 bcdUSB 2.00 bDeviceClass 9 Hub bDeviceSubClass 0 bDeviceProtocol 0 Full speed (or root) hub bMaxPacketSize0 64 idVendor 0x1d6b Linux Foundation idProduct 0x0002 2.0 root hub bcdDevice 5.15 iManufacturer 3 iProduct 2 iSerial 1

Using the lsusb Command with Other Utilities

The lsusb command can be used in combination with other utilities to perform a variety of tasks.

  1. Find the Vendor and Product ID of a USB Device
  2. To find the vendor and product ID of a USB device, use the lsusb command with the -v option and grep for the idVendor and idProduct fields:

    lsusb -v | grep -E 'idVendor|idProduct'
    
    Output
    idVendor 0x046d Logitech, Inc. idProduct 0x0a37 USB Headset H540 idVendor 0x8087 Intel Corp. idProduct 0x0024 Integrated Rate Matching Hub idVendor 0x8087 Intel Corp. idProduct 0x0024 Integrated Rate Matching Hub idVendor 0x1d6b Linux Foundation idProduct 0x0002 2.0 root hub

  3. Find the Device Name of a USB Device
  4. To find the device name of a USB device, use the lsusb command with the -v option and grep for the iProduct field:

    lsusb -v | grep iProduct
    
    Output
    iProduct 2 Logitech USB Headset H540 iProduct 2 EHCI Host Controller iProduct 2 Dell MS116 USB Optical Mouse iProduct 2 usb keyboard

  5. Find the Device Driver of a USB Device
  6. To find the device driver of a USB device, use the lsusb command with the -t option and grep for the device name:

    lsusb -t | grep Unifying
    
    Output
    |__ Port 2: Dev 4, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M

    In this example, the device driver for the USB device is “usbhid”.

  7. Find the Device Node of a USB Device
  8. To find the device node of a USB device, use the lsusb command with the -t option and look for the device name in the /dev directory:

    lsusb -t
    

    Now execute:

    ls /dev/input/
    
    Output
    by-id event0 event10 event2 event4 event6 event8 mice by-path event1 event11 event3 event5 event7 event9 mouse0

    In this example, the device node for the USB device is /dev/input/mouse0.

Conclusion

In this article, you have learned about the `lsusb` command line utility and how to use it to list and display information about USB devices connected to a Linux system. We also saw how to use the lsusb command with other utilities to perform various tasks related to USB devices.

The post lsusb Command in Linux (Display USB device Details) appeared first on TecAdmin.

]]>
https://tecadmin.net/lsusb-command-in-linux/feed/ 0
12 Apt Command Examples in Ubuntu & Debian Linux https://tecadmin.net/apt-command-in-linux/ https://tecadmin.net/apt-command-in-linux/#comments Tue, 03 Jan 2023 15:35:28 +0000 https://tecadmin.net/?p=33552 The apt command is one of the most powerful and versatile tools in the Linux operating system. It provides users with a powerful, yet easy-to-use, package management system that can be used to easily manage and install the software. With the apt command, users can quickly and easily search for, install, upgrade, and uninstall software [...]

The post 12 Apt Command Examples in Ubuntu & Debian Linux appeared first on TecAdmin.

]]>
The apt command is one of the most powerful and versatile tools in the Linux operating system. It provides users with a powerful, yet easy-to-use, package management system that can be used to easily manage and install the software. With the apt command, users can quickly and easily search for, install, upgrade, and uninstall software applications from their systems.

This guide provides a detailed overview of the apt command and explains how to use it to manage software on a Linux system. It explains the different commands and options available and outlines how to use them to manage software, resolve software dependencies, and keep your system running smoothly and efficiently.

The apt package manager is used in several Linux distributions, including:

  • Debian and its derivatives (such as Ubuntu and Linux Mint)
  • Kali Linux
  • Linaro
  • SteamOS

Updating Apt Index (apt update)

Before you can use the Apt package manager, you will need to update the package repositories. The package repositories are online databases that contain information about available packages. To update the package repositories, use the update command:

sudo apt update 

This will download the latest package information from the repositories.

Installing Packages (apt install)

By default, the Apt package manager will install the latest available version of a package. To install a package named `foo` type:

sudo apt install foo 

However, sometimes you may need to install a specific version of a package. To do this, use the = operator followed by the version number when installing the package. For example, to install version 1.2 of the package foo, run the following command:

sudo apt install foo=1.2 

Searching for a Package (apt search)

You can use the `apt search` command followed by the search string. For example, to search for packages related to the word “foo”, run the following command:

sudo apt search foo 

This will display a list of packages that match the keyword.

Keep Your System Up to Date (apt ugprade)

One of the most important best practices for managing packages with the Apt package manager is to keep your system up to date. New versions of packages are released regularly to fix bugs and security vulnerabilities. To update your system, use the upgrade command:

sudo apt upgrade 

This will upgrade all installed packages to their latest available version.

To upgrade a specific package, you should use the apt install command with the `--only-upgrade` option.

sudo apt --only-upgrade install foo 

This will install the latest version of the package only if it is already installed.

Downgrading a Package to a Previous Version

To downgrade a package to a previous version, use the install command with the = operator and the version number of the previous version. For example, to downgrade the package foo to version 1.2, run the following command:

sudo apt install foo=1.2 

Note that this will overwrite the current version of the package, so be sure to make any necessary backups before downgrading.

Remove Packages (apt remove)

You can use the `apt remove` command to remove specific packages. For example, to remove the package foo, run the following command:

sudo apt remove foo 

This will remove the package, but it will leave behind any dependencies that are still needed by other packages.

Removing Unused Dependencies (apt autoremove)

When you install a package, it may bring in other packages as dependencies. These dependencies are required for the package to function correctly. However, once you remove the package, these dependencies may no longer be needed. To remove these unused dependencies, use the autoremove command:

sudo apt autoremove 

This will remove any dependencies that are no longer needed by any installed packages.

Use Apt Pinning to Control Package Upgrades

Apt pinning allows you to control which packages are upgraded and when they are upgraded. This can be useful if you want to prevent a specific package from being upgraded to a newer version. To use Apt pinning, you will need to edit the /etc/apt/preferences file and add a pinning rule.

For example, to prevent the package foo from being upgraded, add the following line to the `/etc/apt/preferences` file:

Package: foo
Pin: version *
Pin-Priority: 1001

This will prevent the package foo from being upgraded, but it will still be updated if a security vulnerability is discovered.

Use Apt Snapshots to Roll Back Package Upgrades

Apt snapshots allow you to roll back package upgrades to a previous version if something goes wrong. To create a snapshot, use the apt-mark command to mark all installed packages as “manual”:

sudo apt-mark manual `apt-mark showmanual` 

Then, use the apt-get command to create a snapshot:

sudo apt-get install apt-rdepends 
sudo apt-rdepends -d --state-show=installed package_name > apt-snapshot.txt 

Replace “package_name” with your package name. This will create a snapshot file called apt-snapshot.txt that contains a list of all installed packages and their dependencies. To roll back to a previous snapshot, use the apt-get install command and specify the snapshot file:

sudo apt-get install --reinstall -y \
      -o APT::Get::ReInstall=true \
      -o APT::Get::Show-Upgraded=true \
      -o Debug::pkgProblemResolver=true \
      -f -V < apt-snapshot.txt 

Show Pacakge Information (apt show)

This command allows you to view all the information about a specific package, including its version, its dependencies, and more. With apt show, you can quickly find out what a certain package does, and whether it's right for your system. You can also check to make sure that you have the latest version of a package, or even downgrade it if necessary. So if you're a Linux user looking for detailed package information.

sudo apt show foo 

So if you're a Linux user looking for detailed package information, you can use `apt show` to find it quickly and easily.

Cleaning the Package Cache (apt clean)

The Apt package manager keeps a cache of all the packages that you have installed or downloaded. Over time, this cache can become large and take up a lot of disk space. To clean the package cache and free up disk space, use the clean command:

sudo apt clean 

This will remove all the packages from the cache that are no longer needed.

Conclusion

In this article, we covered some advanced techniques for using the Apt package manager. We showed you how to install a specific version of a package, upgrade all packages to their latest version, downgrade a package to a previous version, remove unused dependencies, and clean the package cache. These techniques can help you more effectively manage packages on your Linux system.

The post 12 Apt Command Examples in Ubuntu & Debian Linux appeared first on TecAdmin.

]]>
https://tecadmin.net/apt-command-in-linux/feed/ 1
df Command – Check Disk Space in Linux https://tecadmin.net/df-command-in-linux/ https://tecadmin.net/df-command-in-linux/#respond Tue, 20 Dec 2022 05:11:09 +0000 https://tecadmin.net/?p=32569 Do you use Linux? If so, then you know that it is a powerful operating system with a lot of tools and options to help you manage your system. One of the most useful tools that Linux provides is the df command, which allows you to check your disk space. In this blog, we will [...]

The post df Command – Check Disk Space in Linux appeared first on TecAdmin.

]]>
Do you use Linux? If so, then you know that it is a powerful operating system with a lot of tools and options to help you manage your system. One of the most useful tools that Linux provides is the df command, which allows you to check your disk space. In this blog, we will take a look at how to use the df command to check your disk space in Linux.

df Command – Check Disk Space in Linux

The `df` command is a Linux utility that displays information about disk space usage on the system. When used without any options, df shows the amount of available disk space on all mounted file systems.

Here is an example of the `df` command:

df 

Filesystem     1K-blocks     Used   Available Use% Mounted on
/dev/sda1       81120644 74228852   6875408  92% /
tmpfs            4074140        0   4074140   0% /dev/shm

The output shows the file system name (e.g., `/dev/sda1`), the total size of the file system in 1K blocks, the amount of space used, the amount of available space, and the percentage of space used. The last column shows the mount point for the file system.

You can use the following options with the `df` command:

  • `-a`: Shows information about all file systems, including those that have 0 blocks.
  • `-h`: Shows the sizes of file systems in “human-readable” format (e.g., in MB or GB).
  • `-i`: Shows the number of inodes (files and directories) on the file system.
  • `-T`: Shows the type of the file system.
  • `-x`: Exclude a specific file system from the output.

If you want to check the disk space for a specific filesystem, you can use the -T option. This will show you the total size, used space, and free space for the specified filesystem. For example, to check the disk space for the `/dev/sda1` filesystem, you can run the following command:

df -T /dev/sda1 
du Command in Linux (Check Disk Space)
du -T command output

You can also use the `-h` option to get the output in a more human-readable format. This will show the size of the filesystem in kilobytes, megabytes, or gigabytes, rather than in bytes.

df -hT /dev/sda1 
du Command in Linux (Check Disk Space)
du -hT command output

How to Check Available Disk Space with Other Linux Commands

The df command is not the only way to check disk space in Linux. There are a number of other commands that you can use to check disk space.

The du command is a useful tool for checking disk usage. The syntax for this command is as follows:

du [options] [files]

This command will show you how much disk space is being used by a particular file or directory. You can also use the `-h` option to get the output in a more human-readable format.

Another useful command is the `df -i` command. This command will show you the number of inodes available on the filesystem. Inodes are used to store information about files, such as their size and permissions.

Finally, the `df -m` command will show you the amount of available memory on the system. This is useful for checking how much memory is available for applications.

Conclusion

In this blog, we have taken a look at how to use the df command to check your disk space in Linux. We have also looked at some of the options that you can use to customize the output, as well as some other commands that you can use to check disk space.

Using the df command is a great way to keep track of your disk space in Linux. It is a powerful tool that can help you manage your system and make sure that you are not running out of disk space. So, the next time you need to check your disk space in Linux, make sure to use the df command.

I hope you found this blog to be helpful. If you are looking for more information on Linux, then be sure to check out our list of the Top 10 Best Linux Desktop Distributions.

The post df Command – Check Disk Space in Linux appeared first on TecAdmin.

]]>
https://tecadmin.net/df-command-in-linux/feed/ 0
Efficiently Reading a File Line by Line in a Shell Script https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/ https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/#respond Fri, 16 Dec 2022 10:52:21 +0000 https://tecadmin.net/?p=6390 Reading a file line by line is a common task in many shell scripts, as it allows you to process each line of a file separately and perform actions based on the contents of each line. There are several ways to read a file line by line in a Linux shell script, but some methods [...]

The post Efficiently Reading a File Line by Line in a Shell Script appeared first on TecAdmin.

]]>
Reading a file line by line is a common task in many shell scripts, as it allows you to process each line of a file separately and perform actions based on the contents of each line. There are several ways to read a file line by line in a Linux shell script, but some methods are more efficient than others. In this article, we’ll explore some of the most efficient ways to read a file line by line in a Linux shell script.

Using while loop

The most basic way to read a file line by line in a shell script is to use a while loop and the read command. The read command reads a line of input from the file and stores it in a variable, which can then be processed by the script. The while loop allows you to iterate through the lines of the file until the end is reached. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < file.txt

This method is simple and easy to understand, but it has some limitations. One limitation is that the read command can only read one line at a time, so it can be slower for large files with many lines. In addition, the read command can only read from standard input (stdin), so you must use the < operator to redirect the contents of the file to stdin. This can be inconvenient if you need to read from multiple files or if you want to read from a file that is not in the current directory.

Using while loop with cat

A more efficient way to read a file line by line in a shell script is to use the cat command in combination with a while loop. The cat command reads a file and outputs its contents to stdout, which can then be processed by the while loop. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < <(cat file.txt)

This method is more efficient than the read command because it reads the entire file into memory at once, rather than reading one line at a time. This can be faster for large files with many lines. In addition, the cat command can read from any file, not just stdin, so you can use it to read from multiple files or files that are not in the current directory.

Using while loop with sed

Another efficient way to read a file line by line in a shell script is to use the sed command in combination with a while loop. The sed command is a powerful text processing tool that can read a file and output its contents to stdout, one line at a time. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < <(sed -n -e 1p file.txt)

This method is similar to the cat command, but it is more efficient because it only outputs one line at a time. This can be faster for large files with many lines. In addition, the sed command has many options and features that can be used to manipulate the output, so it is a very flexible tool for text processing.

In summary, there are several ways to read a file line by line in a Linux shell script.

The post Efficiently Reading a File Line by Line in a Shell Script appeared first on TecAdmin.

]]>
https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/feed/ 0
Top Command in Linux (System & Process Monitoring) https://tecadmin.net/linux-top-command/ https://tecadmin.net/linux-top-command/#respond Sat, 24 Sep 2022 04:50:51 +0000 https://tecadmin.net/?p=31824 The top command is a Linux command that displays real-time information about your computer’s processes. This information includes how much CPU and memory each process is using. The top command is very helpful when you want to troubleshoot problems with your computer or optimize its performance. While there are many different top commands that can [...]

The post Top Command in Linux (System & Process Monitoring) appeared first on TecAdmin.

]]>
The top command is a Linux command that displays real-time information about your computer’s processes. This information includes how much CPU and memory each process is using. The top command is very helpful when you want to troubleshoot problems with your computer or optimize its performance. While there are many different top commands that can be used on Linux, the most common are ps, netstat, lsof, vmstat, and htop. These top commands can be used to view information about your computer’s processes, view information about your computer’s network connections, view information about open files and the processes that are using them, and more. The specific top command that you use will determine what information you can view.

The Top Command

The top command can help you monitor processes, view information about your computer, and more. Top commands are especially useful if you need to troubleshoot problems with your computer or optimize its performance. Let’s take a look at some of these top commands and how they can be used by Linux users.

Open a terminal on your system and just type “top” and hit Enter.

top 

You will see the running processes and other resource utilization details:

Top command in Linux
Top command in Linux
  • In the output, the first part shows the resource utilization including the Memory, Swap memory, and CPU utilization. Also shows the system uptime.
  • The second part shows the currently running process. It shows many details about any process but the most useful are the PID, CPU, and Memory utilization of any process.
  • Simply press the ‘Q’ button to quit from top command

Change Update Interval

By default, the result updates every 3 seconds. We can overwrite this default value with -d options. For example, to update the results every 10 seconds, type:

top -d 10 

You will notice that the results are updating slowly now. You can also change this at run time as well.

Top Interactive Command Shortcuts

The top comes with many interactive command shortcuts to change the output as per the requirements

  • Press C to show the absolute path of running processes or commands.
  • Press K and enter a PID of the process to kill the running processes.
  • Use the Left and Right arrow keys to shift the display
  • Press N and enter the number to display the N number of processes only.
  • Press S and input the seconds to adjust change delay.

Check the below screenshot to find all the available shortcuts in top command:

Top Command in Linux with Examples
Shortcuts in Linux top command

Modify Display Fields

The default top command shows Process Id (PID), Effective User Name (USER), Priority (PR), Nice Value (NI), Virtual Image (VIRT), Resident Size (RES), Shared Memory (SHR), Process Status (S), CPU Usage (%CPU), Memory Usage (%MEM), CPU Time (TIME+), Command Name (COMMAND). There are many other filed options available to add to the current display. Also you can delete any field from the display or change the order of fields.

For the filed management, run the top command and press the F button. You will see the screen below:

Alter the Top command fields to display
Alter the Top command fields to display

Currently, active fields in the command output are marked with an asterisk (*) in the prefix.

  • Use the keyboard UP and DOWN arrow key buttons to navigate between fields
  • Press the D or Spacebar button to toggle the selection.
  • To change the order of fields in the output. Press the Right arrow to select the field, then use the UP and DOWN arrows to move. Hit Enter button to apply changes
  • You can also change the default sort field. Press the S button to set the default sort filed in the output. Currently, the short field can be seen in the first row of field management options
  • Press Q to go back

Conclusion

The top commands are extremely useful for Linux users. They can help you monitor the performance of your computer, troubleshoot problems, and optimize its performance. With the help of this command, we can easily find the processes consuming high memory and CPU on the system. Get the list of all processes running by the specific user.

The post Top Command in Linux (System & Process Monitoring) appeared first on TecAdmin.

]]>
https://tecadmin.net/linux-top-command/feed/ 0
Bash – How to Get Future Date and Time https://tecadmin.net/bash-how-to-get-future-date-and-time/ https://tecadmin.net/bash-how-to-get-future-date-and-time/#respond Thu, 22 Sep 2022 05:54:20 +0000 https://tecadmin.net/?p=31929 The Linux date command displays the current date and time of the system. While writing the shell scripts, I realise that sometimes we are required to find future dates—for example, dates after 10 days, 2 months, or 1 year, etc. The date command provides an option to display the future dates as described. -d, --date=STRING [...]

The post Bash – How to Get Future Date and Time appeared first on TecAdmin.

]]>
The Linux date command displays the current date and time of the system. While writing the shell scripts, I realise that sometimes we are required to find future dates—for example, dates after 10 days, 2 months, or 1 year, etc.

The date command provides an option to display the future dates as described.

-d, --date=STRING          display time described by STRING, not 'now'

Let’s understand this with some examples:

  • Display current date: Simply type “date” to display the current date and time of system.
    date     
    
    Thu Sep 22 03:58:36 UTC 2022
    
  • Date after 10 days: What will be the date after 10 days? The below command will show you the desired results:
    date -d "+10 days"
    
    Sun Oct  2 03:58:48 UTC 2022
    
  • Date after 3 months: Similarly to find the date after 3 months, type:
    date -d "+3 months "
    
    Thu Dec 22 03:58:58 UTC 2022
    
  • Date after 1 year: What will be the date just after 1 year?
    date -d "+1 year"
    
    Fri Sep 22 03:59:05 UTC 2023
    

These commands are helpful to find the day, month date in the future after a specific duration. We can also format the date on display. Here are a few more examples to view future dates and times.

Command Output Details
date Thu Sep 22 03:58:36 UTC 2022 Display the current date.
date -d “+10 days” Sun Oct 2 03:58:48 UTC 2022 Display date after 10 days.
date -d “tomorrow” Fri Sep 23 03:58:48 UTC 2022 Show tomorrow’s date
date -d “tomorrow + 1” Fri Sep 24 03:58:48 UTC 2022 Show date of the day after tomorrow.
date +”%a” -d “+10 days” Sun Displa the day name after 10 days (eg: Sun, Mon etc)
date +”%b %d, %Y” -d “+10 days” Oct 02, 2022 Display date after 10 days in custom format
date -d “next sun” Sun Sep 25 00:00:00 UTC 2022 Display date on next Sunday
date +”%b” -d “next month” Oct Shwo the next month name (eg: Oct, Nov etc)
date -d “next week” Thu Sep 29 04:46:32 UTC 2022 Show the date on next week of same day
date -d “Oct 12, 2022 +1 week” Wed Oct 19 00:00:00 UTC 2022 Date after 1 week of Oct 12, 2022(or other specific date)
date +”%A” -d “Oct 12, 2022 +1 week” Wednesday Display the day name after one week of Oct 12, 2022.

The post Bash – How to Get Future Date and Time appeared first on TecAdmin.

]]>
https://tecadmin.net/bash-how-to-get-future-date-and-time/feed/ 0
cURL – How to display request headers and response headers https://tecadmin.net/curl-display-request-headers-and-response-headers/ https://tecadmin.net/curl-display-request-headers-and-response-headers/#respond Sat, 10 Sep 2022 10:19:11 +0000 https://tecadmin.net/?p=31577 Request Header and Response Header are both a part of the HTTP protocol, which is the standard used for communication between web browsers and web servers. The Request Header is sent by the browser as part of an HTTP request, and it contains information such as the type of request, the URL of the requested [...]

The post cURL – How to display request headers and response headers appeared first on TecAdmin.

]]>
Request Header and Response Header are both a part of the HTTP protocol, which is the standard used for communication between web browsers and web servers. The Request Header is sent by the browser as part of an HTTP request, and it contains information such as the type of request, the URL of the requested page, and any authentication credentials. The Response Header is sent by the server in response to the request, and it contains information such as the status code of the response, the content type of the page, and any authentication credentials.

Together, the Request and Response Headers help to ensure that data is sent securely and accurately between the browser and the server. Request and Response Headers are essential for web developers as they provide important information for debugging and troubleshooting. If you’re interested in learning more about Request and Response Headers, a good place to start is by reading up on the HTTP protocol.

cURL is a command line utility used to transmit data over different-2 protocols. It is a quick tool for developers to view the request header and response header values of a website.

1. cURL – Get Request Headers

Use --versbose or -v option with the curl command to fetch the request header and response header values as following:

curl --verbose google.com 
how to get request and response header with curl
cURL – get the request header and response header values

2. cURL – Get Response Headers

You can also use curl to fetch the response header values only. Use -I option to get the response header values.

curl -I google.com 
Output:
HTTP/1.1 301 Moved Permanently Location: http://www.google.com/ Content-Type: text/html; charset=UTF-8 Date: Sat, 10 Sep 2022 09:25:56 GMT Expires: Mon, 10 Oct 2022 09:25:56 GMT Cache-Control: public, max-age=2592000 Server: gws Content-Length: 219 X-XSS-Protection: 0 X-Frame-Options: SAMEORIGIN

3. cURL – Get Custom Header Values

Sometimes you may need to fetch the specific header value. That is helpful for scripting and many other tasks. Use the grep command to filter specific values from complete header values. The -F is used to search fixed string and -i is used for case-sensitive search.

curl -I google.com | grep -Fi "Content-Type" 
Output:
Content-Type: text/html; charset=UTF-8

Wrap Up

cURL is a command line utility that is helpful for multiple tasks. We can also use curl to request a server for the details. This tutorial helped you to get the request header and response header values using the curl command line.

The post cURL – How to display request headers and response headers appeared first on TecAdmin.

]]>
https://tecadmin.net/curl-display-request-headers-and-response-headers/feed/ 0
Running Multiple Commands At Once in Linux https://tecadmin.net/running-multiple-commands-at-once-in-linux/ https://tecadmin.net/running-multiple-commands-at-once-in-linux/#respond Sat, 06 Aug 2022 04:35:32 +0000 https://tecadmin.net/?p=30877 We’ll learn about how to execute several commands simultaneously in Linux in this article. Every operator has its own advantages when it comes to separating commands. This tutorial will help a little bit in improving how we execute commands and author shell scripts. The Linux operating system offers a simple command line interface for managing [...]

The post Running Multiple Commands At Once in Linux appeared first on TecAdmin.

]]>
We’ll learn about how to execute several commands simultaneously in Linux in this article. Every operator has its own advantages when it comes to separating commands. This tutorial will help a little bit in improving how we execute commands and author shell scripts.

The Linux operating system offers a simple command line interface for managing the system. There are shells such as Bash, CSH, and Zsh that accept commands from the user and route them to the kernel. A command is used to perform some function on the system. We may also specify multiple shells at once and execute them one after the other.

There are three distinct options available using the separator operators. In the following section, we will look at them in detail.

Operator Syntax Discription
Semicolon (;) command1; command2 Run both commands one by one
Logical AND (&&) command1 && commnd2 Run command2 only if command1 is successfull
Logical OR (||) command1 || command2 Run command2 only if commadn1 failed

Let’s discuss all the options in detail.

Using Semicolon (;)

Semicolons (;) separate commands to guarantee that subsequent commands run regardless of the previous ones’ exit statuses. Use this option to ensure that command runs after the completion of the previous one.

Syntax:

command1;  command2;  commandN

Example:

date; pwd; whoami 

Sat Aug  6 01:56:05 UTC 2022
/home/rahul
rahul

Even though the second command fails because of a permissions error, the third command still executes in the following commands:

date; touch /root/a.txt; whoami 

Sat Aug  6 01:59:31 UTC 2022
touch: cannot touch '/root/a.txt': Permission denied
rahul
Running Multiple Commands At Once in Linux with Semicolon
Running semicolon separated commands

Using Logical AND Operator (&&)

Upon successful execution of the previous command, the next command will also run. The logical AND (&&) operator checks for the exit status of the previous command.

However, if the previous command finished with non-zero exit status, the execution will stop here. No subsequent commands will run in that case

Syntax:

command1 &&  command2 && commandN

Example:

mkdir ./backups && cd ./backups 

The last command will not run if the first command failed due to any reason:

 mkdir /root/backups && cd /root/backups 

mkdir: cannot create directory ‘/root/backups’: Permission denied
Running Multiple Commands At Once in Linux with Logical AND
Using logical AND between multiple commands

Using Logical OR Operator (||)

The logical OR (||) condition checks for the exit status of the previous command and executes the next command only if the previous command failed.

Syntax:

command1 || command2 || commandN

You can use this construct in shell scripts to determine whether a file or command is available. For instance, in a backup script, you can check whether /usr/bin/mysqldump exists or not, and if not, you can print a message or terminate the process.

[ -s /usr/bin/mysqldump ] || echo "command not found" 

Use this to test command or file that isn’t on your system. This is useful for bash scripts that create files if they are missing. You can also stop script execution if required files are missing.

 [ -s /usr/bin/not_a_cmd ] || echo "command not found" 
Running Multiple Commands At Once in Linux with Logical OR
Using logical OR between multiple commands

Conclusion

In this article, we’ll go over how to run multiple commands simultaneously in Linux. We’ll also cover the various operators used to separate commands from one another. Each operator affects the way a command is executed, and each has its own benefits. This tutorial will provide some useful information to anyone interested in enhancing their command-running or shell-script-writing skills.

The post Running Multiple Commands At Once in Linux appeared first on TecAdmin.

]]>
https://tecadmin.net/running-multiple-commands-at-once-in-linux/feed/ 0