Trending February 2024 # How To Manage Users From The Command Line In Linux # Suggested March 2024 # Top 10 Popular

You are reading the article How To Manage Users From The Command Line In Linux updated in February 2024 on the website Eastwest.edu.vn. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How To Manage Users From The Command Line In Linux

One of the central responsibilities of Linux administration is the management of users. Through the use of the command line, user creation can be completed remotely or programmatically. Once you’ve created a user, you can then add them to groups or give them escalated privileges. In addition, you are able to keep an audit trail on what has been done on your server and any potential issues.

If you’ve developed software or programmed for the Web, you might be familiar with the policy of never trusting users. This same premise applies in other areas of computer usage in regards to user involvement. Only give access to those who need it and when they need it. Generous delegation of privileges could allow unspecified and unauthorized access to others’ information and core data.

Viewing existing users

One of the quickest ways to view users is to use the cat (concatenate) or more (pager) commands to view the list of users on the system. The file you will need to view is the “/etc/passwd” file. This file stores all user accounts and user login information.

sudo

cat

/

etc

/

passwd

Utilizing the useradd command

useradd is a low-level binary available on most distros. This command is typically less used due to it being less user-friendly and intuitive compared to the adduser command. However, there are very few differences and either can be used.

To find out more about useradd, run the man command or add --help to get a quick overview.

To add a user using useradd, type useradd and the name of the login you want to create.

sudo

useradd

--create-home

testuser

In the case above, the user “testuser” will be created. By default, this command will only create the user and nothing else. If you need a home directory for this user, append the --create-home flag to create the home directory for the user.

Utilizing the adduser command

The adduser command is a perl script that will create the user similar to the useradd command. What makes it different is that it is an interactive command and will prompt you to set the password, the home directory path, etc. Take note that on some distros, such as Red Hat and CentOS, adduser is a symbolic link to useradd, and on other distro like Arch Linux, adduser comes as a package that is not installed by default.

Using this command will create a group for the user using the user’s login by default. Other defaults can typically be found in the useradd file at “/etc/default”.

In this file you can change default settings for users created with useradd such as the shell and the home directory.

Run the adduser command similar to the following:

This will then prompt you regarding the defaults you want set and ask you for the password.

Passwords and security

Adding a password for a user will require running the passwd command.

sudo

passwd

testuser

Without superuser privileges, running passwd will only change the password of the logged-in user. This command will test the password for complexity. On Ubuntu password requirements are set in the common-password file located in “/ec/pam.d.” More information regarding updating the complexity can be found in the man page for pam-auth-update.

Updating user information

Once a user is on the system, you can review the “/etc/passwd” file to see the user’s information and encrypted password. If you need to make changes to a user, you will need to utilize the usermod command.

As an example, to change the user id for the testuser4 account created above, you would run the command:

sudo

usermod

-u

2024

testuser2

You can then review the changes in the “/etc/passwd” file.

Be careful of changing critical information such as the login name, or as in this case, the user id. Review the man page for usermod to see what you will need to do if those items are changed.

Adding users to group

There are times when you need to add users to a group so they have the necessary permission to run certain tasks.

To add a user to a group:

sudo

usermod

-a

-G

groupname username

Note that the -a flag is necessary to “append” the group for the user. If not, you will risk removing the user from the “sudo” group if the user is supposed to have superuser permission.

Alternatively, you can use the gpasswd command to add/remove user to/from group.

sudo

gpasswd

-a

username groupname

To remove user from a group:

sudo

gpasswd

-d

username groupname Removing users

Similar to the other user commands, deleting a user is prefixed with “user” and the action. In this case you will need to use the userdel command.

Take note that userdel will not remove a user if there are processes using that user’s account.

sudo

userdel testuser4 Viewing user logs

Depending on your distro, you will either check the auth log or the secure log located in “/var/log” to review user logins. This log file will give you logins on your system as soon as they happen. This is a critical element to monitoring events in the case of a breach and just to ensure things are working as desired.

sudo

tail

/

var

/

log

/

auth.log

User management is a crucial part of managing Linux servers if there is more than one person who will use your system. Using the command line will allow you to quickly administer users, as well as have a history of account creation and changes. Perhaps one of the best uses would be to automate creation with a shell script if multiple accounts are needed at once.

Either way, be sure to go through your accounts on a regular basis and remove accounts that are no longer needed. Ensure access is granted only to those who currently need access and monitor your logs frequently.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

You're reading How To Manage Users From The Command Line In Linux

Create Montages And Proof Sheets From The Command Line On Linux

ImageMagick is a suite of tools for Linux which allows you to manipulate images from the command line. The “convert” command allows you to perform image conversions and image transformations, and you can use the “identify” command to view the Exif data in your images. Another tool from the suite is “montage” which allows you to create a montage or proof sheet (or contact sheet) by combining a number of different images, with or without a border or frame.

To create a simple proof sheet, call “montage” with a list of the images to include plus one final filename for the output. For example:

montage chúng tôi chúng tôi chúng tôi chúng tôi will create a montage called “mymontage.jpg” composed of the files chúng tôi chúng tôi and img3.jpg.

You can also use wildcards to include all the pictures in a directory or just those matching the wildcard (e.g. “holiday*.jpg”). Here is how to use all the JPEG images in the current directory:

montage *.jpg chúng tôi default, the “montage” command will try to fit each image into a 120 x 120 thumbnail and then arrange the images (tile them) in the most optimal way. You can override this default and specify a different size for the images. To produce 180×180 thumbnails with 4 pixels on the left and right of each image and 3 pixels below, use:

montage -geometry 180x180+4+3 *.jpg chúng tôi that because the +4 specifies how many pixels are on the left and right of each image, it means that the first thumbnail will be 4 pixels from the left of the contact sheet but the gap between the images will be 8 pixels, 4 on the right of the first image plus 4 on the left of the next image and so on.

To add a frame to each of the images, use the “-frame” option. This option also needs a parameter to define how large the frame should be. For instance, “-frame 5” asks for a frame 5 pixels wide:

montage -frame 5 *.jpg chúng tôi can also add a shadow using the “-shadow” option.

Montage can also produce thumbnails with a Polaroid effect. In essence, the thumbnail is framed with an off-white border and a curl is added to the image. To try the Polaroid transform, use:

montage +polaroid *.jpg chúng tôi that the “+polaroid” option starts with a + sign.

This can then lead to some interesting effects. For example if the spacing between the photos is set to a minus number, the thumbnails can be made to overlap. Combined with the Polaroid effect, this can produce some novel output. Try the following:

montage +polaroid -geometry 180x180-10-3 *.jpg chúng tôi even:

montage +polaroid -geometry 180x180-50-30 *.jpg chúng tôi useful option is “-rotate“. It allows you to specify a rotation for each of the thumbnails. For example, to rotate each picture by 30 degrees, try:

montage -rotate 30 *.jpg chúng tôi is also possible to set the background color of the montage. The color can be set using a color name (e.g. red, aqua, maroon, green, olive and so on) or using a RGB color number (e.g. #FFFF00 for yellow). The ImageMagick website has a full list of supported color names. To set the background to a pale turquoise, use:

montage -background PaleTurquoise *.jpg chúng tôi can even use another image as the background. To do this, use “-texture“, for example:

montage -texture chúng tôi *.jpg chúng tôi “bg.jpg” is the name of the background image file.

The “montage” command can be used to create some quite complex proof sheets. You can get further tips and tricks on the ImageMagick Montage Examples page.

Image credit: sunset montage by BigStockPhoto

Gary Sims

Gary has been a technical writer, author and blogger since 2003. He is an expert in open source systems (including Linux), system administration, system security and networking protocols. He also knows several programming languages, as he was previously a software engineer for 10 years. He has a Bachelor of Science in business information systems from a UK University.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

How To Shutdown Linux Using Command Line And Gui

For a fairly new Linux user, things can be a bit overwhelming in the beginning. While the robustness and unlimited customizability options are attractive, performing basic tasks can be daunting, especially if you are unaware of the proper commands to use. For instance, you need to shut down your system, but as a new user, you are struggling to figure out the right commands to turn off your Linux computer. Though shutting down may seem like an easy task, if done incorrectly, can result in loss of data or worse – could end up corrupting your system. So, if you are a novice Linux user looking to avoid any mishaps, follow this guide to learn the safest methods to shutdown a Linux system, both through the command line and the graphical user interface (GUI).

Safely Shutdown Your Linux System (2023) How to Shutdown Linux Using Command Line

The command line method to turn off a Linux system is preferred by seasoned users as it is fast and provides more options to play around with. This method is especially useful for shutting down Linux servers. Also, this is the most secure way as all the users currently logged in can be notified of the shutdown process so that they can save their work. There are multiple Linux commands you can use to shut down the system.

Use Shutdown Command to Turn Off Linux

The shutdown command is the most common one you can use to power off your Linux system safely. It offers a lot of flexibility since you can use the shutdown command to turn off, halt, or even reboot your PC. When you execute the shutdown command, all the current users are notified of the shutdown process. The basic syntax for shutdown command in Linux is:

OptionDescription-HWrites the final changes to data and then stops the processor from further processing tasks, but the system still stays on with minimal power consumption-PWorks the same as -H, except it cuts off the power to the system-rWrites the final changes to the disk and then reboots the system-kUsed to send a warning message for shutdown-cCancels the pending shutdown

If you use the shutdown command with no parameters, the system will shutdown after one minute.

Shutdown the System at Specific a Time

For example, if the current system time is 15:30 and you want to shutdown the system in the next 10 minutes, then the command in the absolute time will be:

sudo shutdown 15:40

and in relative time the command will be:

Shutdown the System Immediately

sudo shutdown +0

The alternate syntax to shutdown the system immediately is:

sudo shutdown now

Shutdown the System With a Shutdown Message

For example in the above scenario, you can use the command as follows:

sudo shutdown 16:30 "System shutdown scheduled at 16:30. Please do save your work. Thank You."

Once you execute the above command, all the currently logged-in users will see this broadcast message on their wall:

Broadcast message from root@localtarget on pts/1 (Tue 2023-03-21 06:35:46 UTC): System shutdown scheduled at 16:30. Please do save your work. Thank You. The system is going down for poweroff at Tue 2023-03-21 06:45:46 UTC! Shutdown Linux System Using Halt Command

sudo halt -p

Turn Off Linux System Using Poweroff Command

Both the poweroff command and the shutdown command sound very similar, but they have their differences. The poweroff command has a more “aggressive” approach and directly cuts off the power of the system immediately. If used unintentionally, the command can lead to the loss of user data. Whereas, the shutdown command has a more graceful approach, where it first writes the saved work on the disk, stops various CPU processes, and finally cuts off the power to the system. To power down the system with the poweroff command, use this syntax:

sudo poweroff

Shutdown Linux PC Using the init Command

The init command is used to modify the runlevels or the operating state of a process. In Linux and other Unix-like operating systems, “runlevels” are pre-defined states of the system that determine which system services are running. Each runlevel has a specific set of services and daemons that are started or stopped, and the runlevels can be modified to change the state of the system. There are 6 different types of runlevels that can be designated for different situations:

RunlevelDescription0Shuts down the system via normal procedure.1set single user-mode2set multi-user mode without networking3set multi-user mode with networking4used by the user for their specific needs5used to set multi-user mode with networking and GUI6used to reboot the system

sudo init 0

When you select the runlevel 0, the init command takes the more graceful approach of the shutdown command of first writing the changes made to the disk, stopping the CPU processing, and then finally cutting off the system power.

How to Shutdown Linux Using GUI Method

The GUI method to shutdown a system can only work on Linux desktop installations. This method is more common among beginners and probably the easiest of all to work with. Here we have covered how to shutdown Gnome, KDE, and Mate-based Linux systems. But, be assured, you need to follow similar steps on most other Linux Distributions.

Turn Off Gnome-Based System

Shut Down KDE-Based System

1. Open the applications tray from the bottom or press the “Super key” on the keyboard. On most keyboards, the super key is labeled as the “Windows Icon”.

2. Select the “⏻ Quit” option at the bottom of the tray.

Shut Down Mate-Based System

Easy Methods to Shutdown Linux System

How To Find And Manage The Windows Startup Folder For All Users

Find the Startup Folder in Windows 11/10

Finding the Windows Startup folder is easy, as there are multiple ways to do that. Here we discuss how to locate the startup apps using Windows utilities, such as File Explorer, Task Manager, Command Prompt, and Registry Editor.

Locating the Windows Startup Folder in File Explorer

There are two different kinds of startup folders in Windows: one for all users and the other for the current user who’s logged in on the device. Both folder paths can be easily located from the File Explorer window.

To locate the startup folder path for the current user in Windows 11/10, go down the following path: C:UsersUsernameAppDataRoamingMicrosoftWindowsStart MenuProgramsStartup.

Similarly, the Windows 11/10 Startup folder for all users is located at C:ProgramDataMicrosoftWindowsStart MenuProgramsStartUp

Instead of navigating through this long path, you can simply press Win + R to open the Run box, then type shell:common startup, and the above folder will open at that location.

To find the Windows 11/10 Startup folder for the current user, just type shell:startup after Win + R .

Once you’re in the Startup folder, you may be surprised to know that the programs that usually start up with Windows aren’t actually here.

You can manually add program shortcuts here, which we have covered in a later section below, and they’ll start up with your PC from now on. But the apps that have been automatically added by third-party software or Windows 11/10 are controlled by the Task Manager.

Locating the Windows Startup Folder Programs from Task Manager

The startup folder is empty in Windows, as its functions have been superseded by the Task Manager, Registry, Command Prompt and other system apps. That’s why some of the programs which you commonly encounter in startup can’t be located directly from the File Explorer.

For some of these startup programs in Task Manager, their “open file location” is sometimes greyed out. If you want the precise location of these startup files, there are other methods detailed below.

Locating Windows Startup Folder Programs from Command Prompt

You can locate the programs in the Startup Folder from the Windows Command Prompt or the newly launched Windows Terminal.

Open either of these programs in Admin mode and enter the following:

wmic startup get caption

,

command

The above commands and captions will give you a quick summary of all your startup applications and their precise paths which run the startup.

Once their file location is revealed, you can easily search for the individual startup apps in File Explorer.

Locating Startup Programs in Registry

If you can’t access any unwanted startup programs through the above methods, the Windows registry is one of the last places to search.

To access it, press Win + R followed by typing regedit.

Once open, go down the following path to find all the startup programs.

Replace “HKEY_CURRENT_USER” with “HKEY_LOCAL_MACHINE” and go down a similar path to find system apps on startup, such as “RealTek Audio” and “Windows Security Health systray.exe.”

Although you can, you shouldn’t remove a few of the important programs, such as the main browser you’re using or RealTek Audio.

The above methods will help you find any startup folders on your computer, including the ones that seem disabled or hidden from sight.

Manage the Windows 11/10 Startup Folder

There are many things you can do to manage the Startup folder: add/remove the startup programs, delay their individual or collective loading, and somewhat change the launch sequence.

How to Add Programs to Startup Folder in Windows 11/10

If you want to change Windows startup programs by adding them, the fastest way is to create a shortcut of the app in the Windows 11/10 Startup Folder.

Select the Start button and use its menu search to locate the program or application.

Select “Open file location” to navigate to the File Explorer location where the app shortcut is saved.

Open the Startup folder in Windows using Win + R followed by shell:startup.

Drag or copy-paste the program file shortcut to move it to the Startup Folder.

How to Remove Programs from Startup Folder in Windows 11/10

Not all program files will be visible in Startup Folder. Another way to remove programs from your Windows startup is to go to “Startup apps” from the search menu. Here you can disable any other programs you don’t need during Windows boot.

How Can You Delay the Loading of Windows Startup Programs?

Too many startup programs can slow down your Windows device booting. Your Windows desktop screen is held hostage by the CPU-intensive launch screen apps.

You can delay the loading of these programs individually or as a group. For this, consider using a GitHub application called LaunchLater. At less than 2 MB, it’s a very lightweight application and very safe to utilize.

Go to “Code” in the download page and select “download ZIP” to download the program’s ZIP file.

You have to carry out a simple installation. Follow the on-screen instructions until LaunchLater is installed on your computer.

It is no longer possible to change the launch order of Windows startup programs through Windows built-in options. However, you can use the LaunchLater app shared above to introduce a gentle difference in seconds for the launch of individual apps.

Another program you can use for a startup delay in Windows 11/10 is Startup Delayer.

Frequently Asked Questions 1. Which programs should be in the Windows startup menu?

While it’s down to individual choice, it’s a good idea to have a minimum of the following in the Windows startup menu:

RealTek High Definition Audio Driver: without this, your Windows computer is mute. You don’t want to set up your PC audio every time you log in.

The Browser You Use: to connect to the Internet quickly, it’s better to enable your favorite browser in the startup apps.

Many other startup apps which seem important can actually be safely disabled from the Startup location. These include the Windows Defender Icon, Skype, Send to OneNote, Zoom, and Microsoft Teams.

2. How do I remove the startup delay in Windows 11/10?

If you don’t want any startup delay between Windows boot and the launching of apps, there’s a registry hack called “Serialize” that achieves this. The following is a summary of the steps:

Press Win + R and follow it by typing regedit.

Go down this path:

ComputerHKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer

Add a new key called “Serialize” followed by another key called “StartupDelayInMSec” and save its D-Word 32 value as 0.

Restart your PC for the delay to disappear.

To ensure you don’t have any corrupt programs from bad sources in your Startup menu, always download them from this list of safe websites. If you’re struggling, check out this list of fixes for common Windows problems.

Sayak Boral

Sayak Boral is a technology writer with over eleven years of experience working in different industries including semiconductors, IoT, enterprise IT, telecommunications OSS/BSS, and network security. He has been writing for MakeTechEasier on a wide range of technical topics including Windows, Android, Internet, Hardware Guides, Browsers, Software Tools, and Product Reviews.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

How Linux Ping Command Works With Examples

Introduction to Linux Ping

In the Linux ecosystem, the ping is used to check whether the host is reachable or not over the internet protocol. It is working on the ICMP protocol i.e. Internet Control Message Protocol. Ping command utility is cross-platform. Primarily, it is working packet level. Widely, the ping command is also known as the Packet Internet Groper.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of Ping Command:

ping [option] hostname or IP address

ping: We can use the ping keyword in the syntax or command. It will take the two-argument as an option and hostname or IP address. As per the input argument, the ping command will provide the end result of whether the IP or hostname is reachable or not.

option: We can provide the different flags as options that are compatible with the ping command.

hostname or IP address: As per the requirement, we can pass the different hostname or the IP address.

How does Linux Ping Command work?

The ping is widely used to check the host or IP address availability or reachability.

While the source machine is using the ping command, the ping command will follow the below steps:

It is trying to connect the destination host or IP address.

It is calculating the amount of time it is taking from the destination host to the sender or source host.

It is also calculating the average packet loss between the source and destination host.

The ping command is working on the ICMP protocol. It is also known as the Internet Control Message Protocol. With the help of the same protocol, the ping command is sending the series of ECHO REQUEST messages or packets to the destination address and waiting for the reply from destination packages. The destination packets are also replying in the ICPM protocol. If the sources machine will receive the packet or message response from the destination machine. Then only we can say the connection or connectivity is established in between the source or destination servers.

Examples of Linux Ping

Given below are the examples mentioned:

Example #1

Ping Command

Code:

Explanation:

Output:

Example #2

Ping Command – With “-c” Option

By default, the ping command is continuously printing the echo-response on the screen unless and until we do not interrupt it screen. To avoid this condition, we can use the “-c” option with the ping command. It is useful to send the limited ECHO REQUEST packets.

Code:

Explanation:

By default, we are getting the ping response. But we need a limited response or reply from the destination server then we need to use the “-c” option with the response value.

Output:

Example #3

Ping Command – With “i” Option

In ping command, we are having the functionality to send the packets in a specific interval of time.

Note: The default interval time is 1 second.

Code:

Explanation:

As per the above ping command, we are able to send the packets or response to the destination server or host in a specific interval of time i.e., two sec.

Output:

Example #4

Ping Command – With “-f” Option

Sometimes we need to test the network load or network response on the high load. In ping command, we are having the functionality to check the high performance on the network level.

Code:

Explanation:

In ping command, we are sending the huge amount of load in the network via the “-f” option. We can also test the load-carrying capacity of the network.

Output:

Example #5

Ping Command – With “-b” Option

In ping command, we are having the functionality to enable the broadcast.

Code:

ping -b 192.168.1.1

Explanation:

As per the above command, we are able to broadcast in the Linux environment with the help of ping command.

Output:

Example #6

Ping command – With “-s” Option

In the Linux environment, we can test the ping response in different packets sizes. We can define the packet size with the help of “-s” option in the ping command.

Code:

Explanation:

In general, the ping command is using 64 bytes for the source and destination communication. Sometimes due to high traffic or latency, the packets may drop and the necessary packets are not able to reach the source machine. To avoid this condition, we need to use the “-s” option to increase the bytes size in the ping command.

Output:

Example #7

Ping Command – With “-l” Option

In Ping command, we are having the functionality to send the packages at the same time without waiting for the reply from the destination host or IP address.

Code:

Explanation:

Output:

Example #8

Ping Command – With “-v” Option

In the ping command, we are having the functionality to get the verbose output.

Code:

Explanation:

As per the above ping command, we are able to get the ping command output in the verbose mode.

Output:

Example #9

Ping Command – With “-W” Option

In the ping command, we are having the functionality to define the time to wait for response value. The ping command will wait for the destination response at the curtain time period.

Code:

Explanation:

As per the below screenshot, we are waiting for a response from chúng tôi We have defined the waiting time is 10 sec.

Output:

Conclusion

We have seen the uncut concept of “Linux Ping Command” with the proper example, explanation and command with different outputs. The ping command utility is widely used in the multiple platforms. It is the best way to check the connectivity in between the source and destination machine.

Recommended Articles

We hope that this EDUCBA information on “Linux Ping” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Linux Regular Expression

Linux Inode

Linux Network Command

Linux Alias Command

5 Interesting Linux ‘Sort’ Command Examples

If you’re a Linux user, you’re probably familiar with command-line interface (CLI). CLI offers powerful tools to perform complex tasks quickly and efficiently. One of most useful CLI tools is ‘sort’ command. ‘sort’ command allows you to sort lines of text in alphabetical or numerical order, and it offers a variety of options that can make your life easier. In this article, we’ll explore five interesting Linux ‘sort’ command examples.

Sort by Numeric Values

The ‘sort’ command can be used to sort data in numerical order. This is useful when dealing with datasets that include numerical values. To sort by numeric values, use ‘-n’ option. Here’s an example −

$ cat numbers.txt 10 2 30 4 20 $ sort -n numbers.txt 2 4 10 20 30

In this example, ‘sort’ command sorts ‘numbers.txt’ file in numerical order using ‘-n’ option.

Sort in Reverse Order

Sometimes, you may want to sort data in reverse order. For instance, you may want to sort a list of files by date and time, starting with newest files first. To sort in reverse order, use ‘-r’ option. Here’s an example −

$ ls -l total 0 -rw-r--r-- 1 user user 0 Mar 23 14:15 file1.txt -rw-r--r-- 1 user user 0 Mar 23 14:14 file2.txt -rw-r--r-- 1 user user 0 Mar 23 14:13 file3.txt total 0 -rw-r--r-- 1 user user 0 Mar 23 14:15 file1.txt -rw-r--r-- 1 user user 0 Mar 23 14:14 file2.txt -rw-r--r-- 1 user user 0 Mar 23 14:13 file3.txt

In this example, ‘ls -l’ command lists files in current directory, and ‘sort -r’ command sorts list in reverse order.

Sort by Column

The ‘sort’ command can also sort data by specific columns. This is useful when dealing with datasets that have multiple columns of data. To sort by a specific column, use ‘-k’ option. Here’s an example −

$ cat names.txt John Smith,25 Mary Johnson,30 Bob Jones,20 Tom Davis,35 $ sort -t ',' -k 2 names.txt Bob Jones,20 John Smith,25 Mary Johnson,30 Tom Davis,35

In this example, ‘names.txt’ file includes two columns of data separated by a comma. ‘sort’ command uses ‘-t’ option to specify field separator (the comma), and ‘-k 2’ option to sort by second column (the age column).

Sort by Unique Values

The ‘sort’ command can also remove duplicate lines from a dataset. To do this, use ‘-u’ option. Here’s an example −

$ cat fruits.txt apple orange banana orange apple $ sort -u fruits.txt apple banana orange

In this example, ‘sort’ command removes duplicate lines from ‘fruits.txt’ file using ‘-u’ option.

Sort and Merge Files

The ‘sort’ command can also merge multiple sorted files into a single sorted file. This is useful when dealing with large datasets that have been split into multiple files. To merge files, use ‘-m’ option. Here’s an example −

$ cat file1.txt 1 3 5 $ cat file2.txt 2 4 6 $ sort -m chúng tôi file2.txt 1 2 3 4 5 6

In this example, ‘sort’ command merges ‘file1.txt’ and ‘file2.txt’ files into a single sorted file using ‘-m’ option.

Sort by Ignoring Leading Characters

Sometimes, a dataset may have leading characters that you don’t want to consider while sorting. For example, you may have a list of filenames that begin with a date stamp, and you want to sort them by filename only. To ignore leading characters, use ‘-b’ option. Here’s an example −

$ ls 2023-03-22_file1.txt 2023-03-23_file3.txt 2023-03-21_file2.txt 2023-03-22_file1.txt 2023-03-21_file2.txt 2023-03-23_file3.txt

In this example, ‘ls’ command lists files in current directory. ‘sort’ command uses ‘-b’ option to ignore leading spaces, and ‘-t’ option to specify field separator (the underscore). ‘-k 2’ option sorts files by second field (the filename) while ignoring leading date stamp.

Sort by Human-readable Sizes

If you’re working with files or directories, you may want to sort them by size. However, sorting by size in bytes can be difficult to read and compare. To sort by human-readable sizes (e.g. KB, MB, GB), use ‘-h’ option. Here’s an example −

$ du -h 10M file1.txt 100K file2.txt 1G file3.txt 100K file2.txt 10M file1.txt 1G file3.txt

In this example, ‘du’ command displays disk usage of files in current directory in human-readable format using ‘-h’ option. ‘sort’ command sorts files by size in human-readable format using ‘-h’ option.

Sort by Date and Time

If you’re working with files, you may want to sort them by date and time. To sort by date and time, use ‘-t’ option to specify field separator, and ‘-k’ option to sort by date and time column. Here’s an example −

$ ls -l -rw-r--r-- 1 user user 0 Mar 23 14:15 file1.txt -rw-r--r-- 1 user user 0 Mar 22 13:45 file2.txt -rw-r--r-- 1 user user 0 Mar 21 12:30 file3.txt -rw-r--r-- 1 user user 0 Mar 21 12:30 file3.txt -rw-r--r-- 1 user user 0 Mar 22 13:45 file2.txt -rw-r--r-- 1 user user 0 Mar 23 14:15 file1.txt

In this example, ‘ls -l’ command lists files in current directory with their date and time of modification. ‘sort’ command uses ‘-t’ option to specify field separator (a space), and ‘-k 6,7’ option to sort by date and time columns.

Sort by Random Order

Finally, you can also sort data in a random order. This can be useful when testing or generating random data. To sort in random order, use ‘-R’ option. Here’s an example −

$ cat names.txt John Mary Bob Tom $ sort -R

In this example, ‘sort’ command sorts names in ‘names.txt’ file in a random order using ‘-R’ option. This can be useful for generating random test data or shuffling lists.

Conclusion

The ‘sort’ command is a powerful tool for sorting and manipulating data on Linux command line. In this article, we’ve explored five interesting ‘sort’ command examples, including sorting by numeric values, sorting in reverse order, sorting by column, sorting by unique values, and merging sorted files. These examples should give you a good starting point for using ‘sort’ command in your own Linux command-line workflows. Happy sorting!

Update the detailed information about How To Manage Users From The Command Line In Linux on the Eastwest.edu.vn website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!