The Complete Guide to “useradd” Command in Linux – 15 Practical Examples

We all are aware about the most popular command called ‘useradd‘ or ‘adduser‘ in Linux. There are times when a Linux System Administrator asked to create user accounts on Linux  with some specific properties, limitations or comments.

In Linux, a ‘useradd‘ command is a low-level utility that is used for adding/creating user accounts in Linux and other Unix-like operating systems. The ‘adduser‘ is much similar to useradd command, because it is just a symbolic link to it.

add users in linux

useradd command examples

In some other Linux distributions, useradd command may comes with lightly difference version. I suggest you to read your documentation, before using our instructions to create new user accounts in Linux.

When we run ‘useradd‘ command in Linux terminal, it performs following major things:

  1. It edits /etc/passwd, /etc/shadow, /etc/group and /etc/gshadow files for the newly created User account.
  2. Creates and populate a home directory for the new user.
  3. Sets permissions and ownerships to home directory.

Basic syntax of command is:

useradd [options] username

In this article we will show you the most used 15 useradd commands with their practical examples in Linux. We have divided the section into two parts from Basic to Advance usage of command.

  1. Part I: Basic usage with 10 examples
  2. Part II: Advance usage with 5 examples
Part I – 10 Basic Usage of useradd Commands

1. How to Add a New User in Linux

To add/create a new user, all you’ve to follow the command ‘useradd‘ or ‘adduser‘ with ‘username’. The ‘username’ is a user login name, that is used by user to login into the system.

Only one user can be added and that username must be unique (different from other username already exists on the system).

For example, to add a new user called ‘tecmint‘, use the following command.

[root@tecmint ~]# useradd tecmint

When we add a new user in Linux with ‘useradd‘ command it gets created in locked state and to unlock that user account, we need to set a password for that account with ‘passwd‘ command.

[root@tecmint ~]# passwd tecmint
Changing password for user tecmint.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

Once a new user created, it’s entry automatically added to the ‘/etc/passwd‘ file. The file is used to store users information and the entry should be.

tecmint:x:504:504:tecmint:/home/tecmint:/bin/bash

The above entry contains a set of seven colon-separated fields, each field has it’s own meaning. Let’s see what are these fields:

  1. Username: User login name used to login into system. It should be between 1 to 32 charcters long.
  2. Password: User password (or x character) stored in /etc/shadow file in encrypted format.
  3. User ID (UID): Every user must have a User ID (UID) User Identification Number. By default UID 0 is reserved for root user and UID’s ranging from 1-99 are reserved for other predefined accounts. Further UID’s ranging from 100-999 are reserved for system accounts and groups.
  4. Group ID (GID): The primary Group ID (GID) Group Identification Number stored in /etc/group file.
  5. User Info: This field is optional and allow you to define extra information about the user. For example, user full name. This field is filled by ‘finger’ command.
  6. Home Directory: The absolute location of user’s home directory.
  7. Shell: The absolute location of a user’s shell i.e. /bin/bash.

2. Create a User with Different Home Directory

By default ‘useradd‘ command creates a user’s home directory under /home directory with username. Thus, for example, we’ve seen above the default home directory for the user ‘tecmint‘ is ‘/home/tecmint‘.

However, this action can be changed by using ‘-d‘ option along with the location of new home directory (i.e./data/projects). For example, the following command will create a user ‘anusha‘ with a home directory ‘/data/projects‘.

[root@tecmint ~]# useradd -d /data/projects anusha

You can see the user home directory and other user related information like user id, group id, shell and comments.

[root@tecmint ~]# cat /etc/passwd | grep anusha

anusha:x:505:505::/data/projects:/bin/bash

3. Create a User with Specific User ID

In Linux, every user has its own UID (Unique Identification Number). By default, whenever we create a new user accounts in Linux, it assigns userid 500501502 and so on…

But, we can create user’s with custom userid with ‘-u‘ option. For example, the following command will create a user ‘navin‘ with custom userid ‘999‘.

[root@tecmint ~]# useradd -u 999 navin

Now, let’s verify that the user created with a defined userid (999) using following command.

[root@tecmint ~]# cat /etc/passwd | grep tecmint

navin:x:999:999::/home/tecmint:/bin/bash

NOTE: Make sure the value of a user ID must be unique from any other already created users on the system.

4. Create a User with Specific Group ID

Similarly, every user has its own GID (Group Identification Number). We can create users with specific group ID’s as well with -g option.

Here in this example, we will add a user ‘tarunika‘ with a specific UID and GID simultaneously with the help of ‘-u‘ and ‘-g‘ options.

[root@tecmint ~]# useradd -u 1000 -g 500 tarunika

Now, see the assigned user id and group id in ‘/etc/passwd‘ file.

[root@tecmint ~]# cat /etc/passwd | grep tarunika

tarunika:x:1000:500::/home/tarunika:/bin/bash

5. Add a User to Multiple Groups

The ‘-G‘ option is used to add a user to additional groups. Each group name is separated by a comma, with no intervening spaces.

Here in this example, we are adding a user ‘tecmint‘ into multiple groups like adminswebadmin and developer.

[root@tecmint ~]# useradd -G admins,webadmin,developers tecmint

Next, verify that the multiple groups assigned to the user with id command.

[root@tecmint ~]# id tecmint

uid=1001(tecmint) gid=1001(tecmint)
groups=1001(tecmint),500(admins),501(webadmin),502(developers)
context=root:system_r:unconfined_t:SystemLow-SystemHigh

6. Add a User without Home Directory

In some situations, where we don’t want to assign a home directories for a user’s, due to some security reasons. In such situation, when a user logs into a system that has just restarted, its home directory will be root. When such user uses su command, its login directory will be the previous user home directory.

To create user’s without their home directories, ‘-M‘ is used. For example, the following command will create a user ‘shilpi‘ without a home directory.

[root@tecmint ~]# useradd -M shilpi

Now, let’s verify that the user is created without home directory, using ls command.

[root@tecmint ~]# ls -l /home/shilpi

ls: cannot access /home/shilpi: No such file or directory

7. Create a User with Account Expiry Date

By default, when we add user’s with ‘useradd‘ command user account never get expires i.e their expiry date is set to 0 (means never expired).

However, we can set the expiry date using ‘-e‘ option, that sets date in YYYY-MM-DD format. This is helpful for creating temporary accounts for a specific period of time.

Here in this example, we create a user ‘aparna‘ with account expiry date i.e. 27th April 2014 in YYYY-MM-DDformat.

[root@tecmint ~]# useradd -e 2014-03-27 aparna

Next, verify the age of account and password with ‘chage‘ command for user ‘aparna‘ after setting account expiry date.

[root@tecmint ~]# chage -l aparna

Last password change						: Mar 28, 2014
Password expires						: never
Password inactive						: never
Account expires							: Mar 27, 2014
Minimum number of days between password change		        : 0
Maximum number of days between password change		        : 99999
Number of days of warning before password expires		: 7

8. Create a User with Password Expiry Date

The ‘-f‘ argument is used to define the number of days after a password expires. A value of 0 inactive the user account as soon as the password has expired. By default, the password expiry value set to -1 means never expire.

Here in this example, we will set a account password expiry date i.e. 45 days on a user ‘tecmint’ using ‘-e‘ and ‘-f‘ options.

[root@tecmint ~]# useradd -e 2014-04-27 -f 45 tecmint

9. Add a User with Custom Comments

The ‘-c‘ option allows you to add custom comments, such as user’s full namephone number, etc to /etc/passwd file. The comment can be added as a single line without any spaces.

For example, the following command will add a user ‘mansi‘ and would insert that user’s full name, Manis Khurana, into the comment field.

[root@tecmint ~]# useradd -c "Manis Khurana" mansi

You can see your comments in ‘/etc/passwd‘ file in comments section.

[root@tecmint ~]# tail -1 /etc/passwd

mansi:x:1006:1008:Manis Khurana:/home/mansi:/bin/sh

10. Change User Login Shell:

Sometimes, we add users which has nothing to do with login shell or sometimes we require to assign different shells to our users. We can assign different login shells to a each user with ‘-s‘ option.

Here in this example, will add a user ‘tecmint‘ without login shell i.e. ‘/sbin/nologin‘ shell.

[root@tecmint ~]# useradd -s /sbin/nologin tecmint

You can check assigned shell to the user in ‘/etc/passwd‘ file.

[root@tecmint ~]# tail -1 /etc/passwd

tecmint:x:1002:1002::/home/tecmint:/sbin/nologin
Part II – 5 Advance Usage of useradd Commands

11. Add a User with Specific Home Directory, Default Shell and Custom Comment

The following command will create a user ‘ravi‘ with home directory ‘/var/www/tecmint‘, default shell /bin/bashand adds extra information about user.

[root@tecmint ~]# useradd -m -d /var/www/ravi -s /bin/bash -c "TecMint Owner" -U ravi

In the above command ‘-m -d‘ option creates a user with specified home directory and the ‘-s‘ option set the user’s default shell i.e. /bin/bash. The ‘-c‘ option adds the extra information about user and ‘-U‘ argument create/adds a group with the same name as the user.

12. Add a User with Home Directory, Custom Shell, Custom Comment and UID/GID

The command is very similar to above, but here we defining shell as ‘/bin/zsh‘ and custom UID and GID to a user ‘tarunika‘. Where ‘-u‘ defines new user’s UID (i.e. 1000) and whereas ‘-g‘ defines GID (i.e. 1000).

[root@tecmint ~]# useradd -m -d /var/www/tarunika -s /bin/zsh -c "TecMint Technical Writer" -u 1000 -g 1000 tarunika

13. Add a User with Home Directory, No Shell, Custom Comment and User ID

The following command is very much similar to above two commands, the only difference is here, that we disabling login shell to a user called ‘avishek‘ with custom User ID (i.e. 1019).

Here ‘-s‘ option adds the default shell /bin/bash, but in this case we set login to ‘/usr/sbin/nologin‘. That means user ‘avishek‘ will not able to login into the system.

[root@tecmint ~]# useradd -m -d /var/www/avishek -s /usr/sbin/nologin -c "TecMint Sr. Technical Writer" -u 1019 avishek

14. Add a User with Home Directory, Shell, Custom Skell/Comment and User ID

The only change in this command is, we used ‘-k‘ option to set custom skeleton directory i.e. /etc/custom.skell, not the default one /etc/skel. We also used ‘-s‘ option to define different shell i.e. /bin/tcsh to user ‘navin‘.

[root@tecmint ~]# useradd -m -d /var/www/navin -k /etc/custom.skell -s /bin/tcsh -c "No Active Member of TecMint" -u 1027 navin

15. Add a User without Home Directory, No Shell, No Group and Custom Comment

This following command is very different than the other commands explained above. Here we used ‘-M‘ option to create user without user’s home directory and ‘-N‘ argument is used that tells the system to only create username (without group). The ‘-r‘ arguments is for creating a system user.

[root@tecmint ~]# useradd -M -N -r -s /bin/false -c "Disabled TecMint Member" clayton

For more information and options about useradd, run ‘useradd‘ command on the terminal to see available options.

Read Also15 usermod Command Examples

Source

Add Rainbow Colors to Linux Command Output in Slow Motion

In this article, we will review a cool and simple way of giving a command screen output a rainbow colors and slowing down its output speed as well for one reason or the other.

The lolcat program is used for the above purpose. It basically functions by concatenating files, or standard input, to standard output in a similar way as the cat command, overrides the default screen output color of a particular command and adds rainbow coloring to it.

How to Install Lolcat Program in Linux

Lolcat program is available on almost all modern Linux distributions from its default repository, but the available version bit older. Alternatively you can install latest version of lolcat from git repository using this following guide.

  1. Install Lolcat to Output Rainbow Of Colors in Linux Terminal

Once lolcat installed, the basic syntax for running lolcat is:

$ lolcat [options] [files] ...

It comes with several options that control its behavior, below are a few of the most considerable flags we will emphasis for the scope of this guide:

  1. -a – passes every input line through an animation effect.
  2. -d – specifies the duration (number of steps before displaying next line) of the animation effect, the default value is 12.
  3. -s – it specifies the speed (frame rate- number of steps per second) of the animation effect, default value is 20.
  4. -f – enables forcing of coloring in case standard output is not a tty.

You can find more options in the lolcat man page:

$ man lolcat 

How to Use Lolcat in Linux

To use lolcat, simply pipe the output of any relevant command to it and watch the magic.

For example:

$ ls -l | lolcat -as 25

colorful Linux Terminal Output

Besides you can alter the default speed, in the following command, we will use a relatively slow speed of 10steps per second:

$ ls -l | lolcat -as 10

You can use any command with lolcat display output in colorful fashion on Linux terminal, few commands say ps, date and cal as:

$ ps | lolcat
$ date | lolcat
$ cal | lolcat

In this article, we have looked at how to significantly reduce the speed of a command screen output and give it a rainbow coloring effect.

As usual, you can address to us any questions or comments concerning this article via the feedback section below. Lastly, you can mention to us any useful Linux commands you have discovered there.

Source

Newsroom – A Modern CLI to Get Your Favorite News in Linux

If you are a command-line addict like me, then you would always want to do everything such as controlling your Linux systems (local or remote), programming, searching Google using Googler, playing text-based games, reading your favorite news and much more from within a terminal window.

Okay, Linux newbies (or possibly any other Linux users out there) are probably asking, “how can i get latest news from the command-line?” In this article, we are going to show you how to do this using Newsroom (similar to Newsboat – a RSS/Atom Feed reader for Linux console).

Read AlsoCricket-CLI – Watch Live Cricket Scores in Linux Terminal

Newsroom is a simple, free open-source modern command-line tool to get your favorite news in Linux. It is developed using JavaScript (NodeJS to be specific), so it is cross-platform and runs on Linux systems, Mac OSX as well as Windows.

The default newsroom sources are: hackernews, techcrunch, inside, bnext, ithome, wanqu, nodeweekly, codetengu and gankio. You can configure your own sources via OPML (Outline Processor Markup Language) – an XML-based format designed for exchange of outline-structured information between applications running on different operating systems and environments.

Linux Terminal Newsreader

Requirements:

  1. NPM – Default NodeJS package manager; you can install NodeJS and NPM at once on your Linux system.

How to Install Newsroom in Linux Systems

Once you have NPM installed on your system, you install newsroom with root privileges using the sudo command, as follows (the -g switch means install globally: to be used by all users on the system):

$ sudo npm install -g newsroom-cli

Once you have successfully installed newsroom, the CLI will register the newsroom and nr commands in your shell. You can start using it as follows, it will take you to an interactive command line interface where you can choose your news source:

$ newsroom 

News Sources

News Sources

Use the Up and Down arrows to select a news source from a list of predefined sources, as shown below.

Select News Source

Select News Source

After choosing a news source, all news titles will be shown as in the following screen shot, then you can select an item by pressing the Space bar, after making a selection, the item will be indicated by a green colored bullet, as shown in the screen shot below. You can press Enter to read it in detail from a web browser.

Select News Topic

Select News Topic

To terminate the command-line, type [Ctrl+C].

You can also provide the source you want to get news from and the number of news items to be displayed as shown.

$ newsroom [news_source] [number_of_news_items]

For example:

$ newsroom hackernews 3

Last but not least, you can also use your own awesome OPML file, as follows. This way, you can add your own news sources such as tecmint.comfossmint.com, etc.

$ newsroom -o <your-awesome-list.opml>

To view the newsroom help message, use the command below.

$ newsroom --help

For more information check out Newsroom Github repository and learn how to create OPML file.

Newsroom is a great way to get your favorite news in Linux on the command-line. Try it out and share your thoughts about it, with us via the feedback form below.

Source

Rename All Files and Directory Names to Lowercase in Linux

This guide will show you how to rename all files and directories names to lowercase in Linux.

Read AlsoHow to Find Out Top Directories and Files (Disk Space) in Linux

There are several ways to achieve this, but we’ll explain two of the most efficient and reliable methods. For the purpose of this guide, we have used a directory named Files which has the following structure:

# find Files -depth

List Directory Structure

List Directory Structure

1. Using find, xargs and rename Commands Together

rename is a simple command line utility for renaming several files at once in Linux. You can use it together with find utility to rename all files or subdirectories in a particular directory to lowercase as follows:

$ find Files -depth | xargs -n 1 rename -v 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \;

Explanation of options used in the above command.

  • -depth – lists each directory’s contents before the directory itself.
  • -n 1 – instructs xargs to use at most one argument per command line from find output.

Sample output after renaming files and subdirectories to lowercase in Files directory.

Rename Files and Directory Names to Lowercase

Rename Files and Directory Names to Lowercase

Another alternative way using the find and mv commands in a script as explained below.

2. Using find and mv Commands in Shell Script

First create your script (you can name it anything you prefer):

$ cd ~/bin
$ vi rename-files.sh

Then add the code below in it.

#!/bin/bash
#print usage 
if [ -z $1 ];then
        echo "Usage :$(basename $0) parent-directory"
        exit 1
fi

#process all subdirectories and files in parent directory
all="$(find $1 -depth)"



for name in ${all}; do
        #set new name in lower case for files and directories
        new_name="$(dirname "${name}")/$(basename "${name}" | tr '[A-Z]' '[a-z]')"

        #check if new name already exists
        if [ "${name}" != "${new_name}" ]; then
                [ ! -e "${new_name}" ] && mv -T "${name}" "${new_name}"; echo "${name} was renamed to ${new_name}" || echo "${name} wasn't renamed!"
        fi
done

echo
echo
#list directories and file new names in lowercase
echo "Directories and files with new names in lowercase letters"
find $(echo $1 | tr 'A-Z' 'a-z') -depth

exit 0

Save and close the file, then make the script executable and run it:

$ chmod +x rename-files.sh
$ rename-files.sh Files     #Specify Directory Name

Lowercase File Names Using Script

Lowercase File Names Using Script

You may also like to read these following related articles.

  1. Explanation of “Everything is a File” and Types of Files in Linux
  2. fswatch – Monitors Files and Directory Changes or Modifications in Linux
  3. Fasd – A Commandline Tool That Offers Quick Access to Files and Directories
  4. FSlint – How to Find and Remove Duplicate Files in Linux

In this guide, we expalined you how to rename all files and directories to lowercase in Linux. If get any errors, please hit us up via the feedback form below. You can as well offer us any other methods of doing the same.

Source

Linux zcat Command Examples for Newbies

Normally, files compressed using gzip can be restored to their original form using gzip -d or gunzip commands. What if you want to view the contents of a compressed file without uncompressing it? For this purpose, you need the zcat command utility.

Read Also18 tar Command Examples in Linux

Zcat is a command line utility for viewing the contents of a compressed file without literally uncompressing it. It expands a compressed file to standard output allowing you to have a look at its contents. In addition, zcat is identical to running gunzip -c command. In this guide, we will explain zcat command examples for beginners.

1. The first example shows how to view contents of a normal file using cat command, compress it using gzip command and view the contents of the zipped file using zcat as shown.

$ cat users.list 
$ gzip users.list
$ zcat users.list.gz

View Compressed File Contents in Linux

View Compressed File Contents in Linux

2. To view multiple compressed files, use the following command with filenames as shown.

$ zcat users.list.gz apps.list.gz

View Multiple Compressed Files Content in Linux

View Multiple Compressed Files Content in Linux

3. To view contents of normal files use the -f flag, similar to cat command, for example.

$ zcat -f users.list

View Linux File Contents

View Linux File Contents

4. To enable pagination, you can use the more and less commands as shown (Also read: Why ‘less’ is Faster Than ‘more’ Command in Linux).

$ zcat users.list.gz | more
$ zcat users.list.gz | less

5. To get the properties (compressed size, uncompressed size, ratio – compression ratio (0.0% if unknown), uncompressed_name (name of the uncompressed file) of a compressed file, use the -l flag.

$ zcat -l users.list.gz  

View Compressed File Properties in Linux

View Compressed File Properties in Linux

6. To suppress all warnings, use the -q flag as shown.

$ zcat -q users.list.gz

For more information, see the zcat man page.

$ man zcat

You might also like to read these following related articles.

  1. ccat – Show ‘cat Command’ Output with Syntax Highlighting or Colorizing
  2. How to Use ‘cat’ and ‘tac’ Commands with Examples in Linux
  3. Manage Files Effectively using head, tail and cat Commands in Linux
  4. How to Backup or Clone Linux Partitions Using ‘cat’ Command

That’s all! In this short article, we’ve explained zcat command examples for beginners. Share your thoughts with us in the comments section below.

Source

How to Permanently Disable Swap in Linux

Swapping or swap space represents a physical memory page that lives on top of disk partition or a special disk file used for extending the RAM memory of a system when the physical memory fills up.

Using this method of extending RAM resources, inactive memory pages are frequently dumped into the swap area when no RAM is available. However, do to the spinning speed of classical hard disks, swap space is way lower in transfer speeds and access time compared to RAM.

On newer machines with fast SSD hard disks, reserving a small partition for swapping can greatly improve access time and speed transfer compared to classical HDD, but the speed is still more magnitudes lower than RAM memory. Some suggest that the swap space should be set as twice the amount of machine RAM. However, on systems with more than 4 GB or RAM, swap space should be set between 2 or 4 GB.

In case your server has sufficient RAM memory or does not require the use of swap space or the swapping greatly decreases your system performance, you should consider disabling the swap area.

Before actually disabling swap space, first you need to visualize your memory load degree and then identify the partition that holds the swap area, by issuing the below commands.

# free -h 

Look for Swap space used size. If the used size is 0B or close to 0 bytes, it can be assumed that swap space is not used intensively and can be safety disabled.

Check Swap Space

Check Swap Space

Next, issue following blkid command, look for TYPE=”swap” line in order to identify the swap partition, as shown in the below screenshot.

# blkid 

Check Swap Partition Type

Check Swap Partition Type

Again, issue the following lsblk command to search and identify the [SWAP] partition as shown in the below screenshot.

# lsblk

Search Confirm Swap Partition

Search Confirm Swap Partition

After you’ve identified the swap partition or file, execute the below command to deactivate the swap area.

# swapoff /dev/mapper/centos-swap  

Or disable all swaps from /proc/swaps

# swapoff -a 

Run free command in order to check if the swap area has been disabled.

# free -h

Disable Swap Partition

Disable Swap Partition

In order to permanently disable swap space in Linux, open /etc/fstab file, search for the swap line and comment the entire line by adding a # (hashtag) sign in front of the line, as shown in the below screenshot.

# vi /etc/fstab

Disable Swap Partition Permanently

Disable Swap Partition Permanently

Afterwards, reboot the system in order to apply the new swap setting or issuing mount -a command in some cases might do the trick.

# mount -a

After system reboot, issuing the commands presented in the beginning of this tutorial should reflect that the swap area has been completely and permanently disabled in your system.

# free -h
# blkid 
# lsblk

Source

8 Practical Examples of Linux “Touch” Command

In Linux every single file is associated with timestamps, and every file stores the information of last access time, last modification time and last change time. So, whenever we create new file, access or modify an existing file, the timestamps of that file automatically updated.

Linux Touch Command

Linux Touch Command Examples

In this article we will cover some useful practical examples of Linux touch command. The touch command is a standard program for Unix/Linux operating systems, that is used to create, change and modify timestamps of a file. Before heading up for touch command examples, please check out the following options.

Touch Command Options

  1. -a, change the access time only
  2. -c, if the file does not exist, do not create it
  3. -d, update the access and modification times
  4. -m, change the modification time only
  5. -r, use the access and modification times of file
  6. -t, creates a file using a specified time

1. How to Create an Empty File

The following touch command creates an empty (zero byte) new file called sheena.

# touch sheena

2. How to Create Multiple Files

By using touch command, you can also create more than one single file. For example the following command will create 3 files named, sheenameena and leena.

# touch sheena meena leena

3. How to Change File Access and Modification Time

To change or update the last access and modification times of a file called leena, use the -a option as follows. The following command sets the current time and date on a file. If the leena file does not exist, it will create the new empty file with the name.

# touch -a leena

The most popular Linux commands such as find command and ls command uses timestamps for listing and finding files.

4. How to Avoid Creating New File

Using -c option with touch command avoids creating new files. For example the following command will not create a file called leena if it does not exists.

# touch -c leena

5. How to Change File Modification Time

If you like to change the only modification time of a file called leena, then use the -m option with touch command. Please note it will only updates the last modification times (not the access times) of the file.

# touch -m leena

6. Explicitly Set the Access and Modification times

You can explicitly set the time using -c and -t option with touch command. The format would be as follows.

# touch -c -t YYDDHHMM leena

For example the following command sets the access and modification date and time to a file leena as 17:30(17:30 p.m.) December 10 of the current year (2012).

# touch -c -t 12101730 leena

Next verify the access and modification time of file leena, with ls -l command.

# ls -l

total 2
-rw-r--r--.  1 root    root   0 Dec 10 17:30 leena

7. How to Use the time stamp of another File

The following touch command with -r option, will update the time-stamp of file meena with the time-stamp of leena file. So, both the file holds the same time stamp.

# touch -r leena meena

8. Create a File using a specified time

If you would like to create a file with specified time other than the current time, then the format should be.

# touch -t YYMMDDHHMM.SS tecmint

For example the below command touch command with -t option will gives the tecmint file a time stamp of 18:30:55 p.m. on December 102012.

# touch -t 201212101830.55 tecmint

We’ve almost covered all the options available in the touch command for more options use “man touch“. If we’ve still missed any options and you would like to include in this list, please update us via comment box.

Source

Find Top Running Processes by Highest Memory and CPU Usage in Linux

I remember once reading that efficient system administrators are lazy people. The reason is not that they’re not doing their job or wasting their time – it is mostly because they have automated a good deal of their routine tasks. Thus, they don’t have to babysit their servers and can use their time to learn new technologies and always stay at the top of their game.

Part of automating your tasks, is learning how to get a script do what you would have to do yourself otherwise. Continually adding commands to your own knowledge base is just as important.

For that reason, in this article we will share a trick to find out, which processes are consuming lots of Memory and CPU utilization in Linux.

Find Linux Processes By RAM and CPU Usage

Find Linux Processes By RAM and CPU Usage

That said, let’s dive in and get started.

Check Top Processes sorted by RAM or CPU Usage in Linux

The following command will show the list of top processes ordered by RAM and CPU use in descendant form (remove the pipeline and head if you want to see the full list):

# ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head
Sample Output
PID  	PPID 	CMD                      	%MEM 	%CPU
2591	2113 	/usr/lib/firefox/firefox    7.3 	43.5
2549   2520 	/usr/lib/virtualbox/Virtual 3.4  	8.2
2288       1 	/home/gacanepa/.dropbox-dis	1.4	0.3
1889   1543	c:\TeamViewer\TeamViewer.ex	1.0	0.2
2113	1801	/usr/bin/cinnamon		0.9	3.5
2254	2252	python /usr/bin/linuxmint/m	0.3	0.0
2245	1801	nautilus -n			0.3	0.1
1645	1595	/usr/bin/X :0 -audit 0 -aut	0.3	2.5

Find Top Processes By RAM and CPU Usage

Find Top Processes By RAM and CPU Usage

Brief explanation of above options used in above command.

The -o (or –format) option of ps allows you to specify the output format. A favorite of mine is to show the processes’ PIDs (pid), PPIDs (pid), the name of the executable file associated with the process (cmd), and the RAM and CPU utilization (%mem and %cpu, respectively).

Additionally, I use --sort to sort by either %mem or %cpu. By default, the output will be sorted in ascendant form, but personally I prefer to reverse that order by adding a minus sign in front of the sort criteria.

To add other fields to the output, or change the sort criteria, refer to the OUTPUT FORMAT CONTROL section in the man page of ps command.

Don’t Miss: Find Top 15 Processes by Memory Usage with ‘top’ in Batch Mode

Don’t Miss: Find top 10 Directories Disk Size in Linux

Summary

Monitoring process is one of the numerous tasks of a Linux server system administrator, in this tip, we looked at how you list processes on your system and sort them according to RAM and CPU use in descendant form using the ps utility.

Source

10 Screen Command Examples to Manage Linux Terminals

Screen is a full-screen software program that can be used to multiplexes a physical console between several processes (typically interactive shells). It offers a user to open several separate terminal instances inside a one single terminal window manager.

The screen application is very useful, if you are dealing with multiple programs from a command line interface and for separating programs from the terminal shell. It also allows you to share your sessions with others users and detach/attach terminal sessions.

Linux Screen Commands

Screen Command Examples

On my Ubuntu 10.04 Server Edition, Screen has been installed by default. But, in Linux Mint does not have screen installed by default, I need to install it first using apt-get command before using it. Please follow your distribution installation procedure to install screen.

# apt-get install screen (On Debian based Systems)
# yum install screen (On RedHat based Systems)

Actually, Screen is a very good command in Linux which is hidden inside hundreds of Linux commands. Let’s start to see the function of Screen.

Start screen for the first time

Just type screen at the command prompt. Then the screen will show with interface exactly as the command prompt.

pungki@mint ~ $ screen

Show screen parameter

When you enter the screen, you can do all your work as you are in the normal CLI environment. But since the screen is an application, so it have command or parameters.

Type “Ctrl-A” and “?” without quotes. Then you will see all commands or parameters on screen.

                                                             Screen key bindings, page 1 of 1.

                                                             Command key:  ^A   Literal ^A:  a

  break       ^B b         flow        ^F f         lockscreen  ^X x         pow_break   B            screen      ^C c         width       W
  clear       C            focus       ^I           log         H            pow_detach  D            select      '            windows     ^W w
  colon       :            hardcopy    h            login       L            prev        ^H ^P p ^?   silence     _            wrap        ^R r
  copy        ^[ [         help        ?            meta        a            quit        \            split       S            writebuf    >
  detach      ^D d         history     { }          monitor     M            readbuf     <            suspend     ^Z z         xoff        ^S s
  digraph     ^V           info        i            next        ^@ ^N sp n   redisplay   ^L l         time        ^T t         xon         ^Q q
  displays    *            kill        K k          number      N            remove      X            title       A
  dumptermcap .            lastmsg     ^M m         only        Q            removebuf   =            vbell       ^G
  fit         F            license     ,            other       ^A           reset       Z            version     v

^]  paste .
"   windowlist -b
-   select -
0   select 0
1   select 1
2   select 2
3   select 3
4   select 4
5   select 5
6   select 6
7   select 7
8   select 8
9   select 9
I   login on
O   login off
]   paste .

To get out of the help screen, you can press “space-bar” button or “Enter“. (Please note that all shortcuts which use “Ctrl-A” is done without quotes).

Detach the screen

One of the advantages of screen that is you can detach it. Then, you can restore it without losing anything you have done on the screen. Here’s the sample scenario:

You are in the middle of SSH-on your server. Let’s say that you are downloading 400MB patch for your system using wget command.

The download process is estimated to take 2 hours long. If you disconnect the SSH session, or suddenly the connection lost by accident, then the download process will stop. You have to start from the beginning again. To avoid that, we can use screen and detach it.

Take a look at this command. First, you have to enter the screen.

pungki@mint ~ $ screen

Then you can do the download process. For examples on my Linux Mint, I am upgrading my dpkg package using apt-get command.

pungki@mint ~ $ sudo apt-get install dpkg
Sample Output
Reading package lists... Done
Building dependency tree      
Reading state information... Done
The following packages will be upgraded:
  dpkg
1 upgraded, 0 newly installed, 0 to remove and 1146 not upgraded.
Need to get 2,583 kB of archives.
After this operation, 127 kB of additional disk space will be used.
Get:1 http://debian.linuxmint.com/latest/ testing/main dpkg i386 1.16.10 [2,583 kB]
47% [1 dpkg 1,625 kB/2,583 kB 47%]                                        14,7 kB/s

While downloading in progress, you can press “Ctrl-A” and “d“. You will not see anything when you press those buttons. The output will be like this:

[detached from 5561.pts-0.mint]
pungki@mint ~ $

Re-attach the screen

After you detach the screen, let say you are disconnecting your SSH session and going home. In your home, you start to SSH again to your server and you want to see the progress of your download process. To do that, you need to restore the screen. You can run this command:

pungki@mint ~ $ screen -r

And you will see that the process you left is still running.

When you have more than 1 screen session, you need to type the screen session ID. Use screen -ls to see how many screen are available.

pungki@mint ~ $ screen -ls
Sample Output
pungki@mint ~ $ screen -ls
There are screens on:
        7849.pts-0.mint (10/06/2013 01:50:45 PM)        (Detached)
        5561.pts-0.mint (10/06/2013 11:12:05 AM)        (Detached)
2 Sockets in /var/run/screen/S-pungki

If you want to restore screen 7849.pts-0.mint, then type this command.

pungki@mint ~ $ screen -r 7849

Using Multiple Screen

When you need more than 1 screen to do your job, is it possible? Yes it is. You can run multiple screen window at the same time. There are 2 (two) ways to do it.

First, you can detach the first screen and the run another screen on the real terminal. Second, you do nested screen.

Switching between screens

When you do nested screen, you can switch between screen using command “Ctrl-A” and “n“. It will be move to the next screen. When you need to go to the previous screen, just press “Ctrl-A” and “p“.

To create a new screen window, just press “Ctrl-A” and “c“.

Logging whatever you do

Sometimes it is important to record what you have done while you are in the console. Let say you are a Linux Administrator who manage a lot of Linux servers.

With this screen logging, you don’t need to write down every single command that you have done. To activate screen logging function, just press “Ctrl-A” and “H“. (Please be careful, we use capital ‘H’ letter. Using non capital ‘h’, will only create a screenshot of screen in another file named hardcopy).

At the bottom left of the screen, there will be a notification that tells you like: Creating logfile “screenlog.0“. You will find screenlog.0 file in your home directory.

This feature will append everything you do while you are in the screen window. To close screen to log running activity, press “Ctrl-A” and “H” again.

Another way to activate logging feature, you can add the parameter “-L” when the first time running screen. The command will be like this.

pungki@mint ~ $ screen -L

Lock screen

Screen also have shortcut to lock the screen. You can press “Ctrl-A” and “x” shortcut to lock the screen. This is handy if you want to lock your screen quickly. Here’s a sample output of lock screen after you press the shortcut.

Screen used by Pungki Arianto  on mint.
Password:

You can use your Linux password to unlock it.

Add password to lock screen

For security reason, you may want to put the password to your screen session. A Password will be asked whenever you want to re-attach the screen. This password is different with Lock Screen mechanism above.

To make your screen password protected, you can edit “$HOME/.screenrc” file. If the file doesn’t exist, you can create it manually. The syntax will be like this.

password crypt_password

To create “crypt_password” above, you can use “mkpasswd” command on Linux. Here’s the command with password “pungki123“.

pungki@mint ~ $ mkpasswd pungki123
l2BIBzvIeQNOs

mkpasswd will generate a hash password as shown above. Once you get the hash password, you can copy it into your “.screenrc” file and save it. So the “.screenrc” file will be like this.

password l2BIBzvIeQNOs

Next time you run screen and detach it, password will be asked when you try to re-attach it, as shown below:

pungki@mint ~ $ screen -r 5741
Screen password:

Type your password, which is “pungki123” and the screen will re-attach again.

After you implement this screen password and you press “Ctrl-A” and “x” , then the output will be like this.

Screen used by Pungki Arianto  on mint.
Password:
Screen password:

A Password will be asked to you twice. First password is your Linux password, and the second password is the password that you put in your .screenrc file.

Leaving Screen

There are 2 (two) ways to leaving the screen. First, we are using “Ctrl-A” and “d” to detach the screen. Second, we can use the exit command to terminating screen. You also can use “Ctrl-A” and “K” to kill the screen.

That’s some of screen usage on daily basis. There are still a lot of features inside the screen command. You may see screen man page for more detail.

Source

Cron Vs Anacron: How to Schedule Jobs Using Anacron on Linux

In this article, we will explain cron and anacron and also shows you how to setup anacron on Linux. We will as well cover a comparison of these two utilities.

To schedule a task on given or later time, you can use the ‘at’ or ‘batch’ commands and to set up commands to run repeatedly, you can employ the cron and anacron facilities.

Cron – is a daemon used to run scheduled tasks such as system backups, updates and many more. It is suitable for running scheduled tasks on machines that will run continuously 24X7 such as servers.

The commands/tasks are scripted into cron jobs which are scheduled in crontab files. The default system crontab file is /etc/crontab, but each user can also create their own crontab file that can launch commands at times that the user defines.

To create a personal crontab file, simply type the following:

$ crontab -e

How to Setup Anacron in Linux

Anacron is used to run commands periodically with a frequency defined in days. It works a little different from cron; assumes that a machine will not be powered on all the time.

It is appropriate for running daily, weekly, and monthly scheduled jobs normally run by cron, on machines that will not run 24-7 such as laptops and desktops machines.

Assuming you have a scheduled task (such as a backup script) to be run using cron every midnight, possibly when your asleep, and your desktop/laptop is off by that time. Your backup script will not be executed.

However, if you use anacron, you can be assured that the next time you power on the desktop/laptop again, the backup script will be executed.

How Anacron Works in Linux

anacron jobs are listed in /etc/anacrontab and jobs can be scheduled using the format below (comments inside anacrontab file must start with #).

period   delay   job-identifier   command

From the above format:

  • period – this is the frequency of job execution specified in days or as @daily, @weekly, or @monthly for once per day, week, or month. You can as well use numbers: 1 – daily, 7 – weekly, 30 – monthly and N – number of days.
  • delay – it’s the number of minutes to wait before executing a job.
  • job-id – it’s the distinctive name for the job written in log files.

To view example files, type:

$ ls -l /var/spool/anacron/

total 12
-rw------- 1 root root 9 Jun  1 10:25 cron.daily
-rw------- 1 root root 9 May 27 11:01 cron.monthly
-rw------- 1 root root 9 May 30 10:28 cron.weekly
  • command – it’s the command or shell script to be executed.
This is what practically happens:
  • Anacron will check if a job has been executed within the specified period in the period field. If not, it executes the command specified in the command field after waiting the number of minutes specified in the delay field.
  • Once the job has been executed, it records the date in a timestamp file in the /var/spool/anacron directory with the name specified in the job-id (timestamp file name) field.

Let’s now look at an example. This will run the /home/aaronkilik/bin/backup.sh script everyday:

@daily    10    example.daily   /bin/bash /home/aaronkilik/bin/backup.sh

If the machine is off when the backup.sh job is expected to run, anacron will run it 10 minutes after the machine is powered on without having to wait for another 7 days.

There are two important variables in the anacrontab file that you should understand:

  • START_HOURS_RANGE – this sets time range in which jobs will be started (i.e execute jobs during the following hours only).
  • RANDOM_DELAY – this defines the maximum random delay added to the user defined delay of a job (by default it’s 45).

This is how your anacrontab file would possibly look like.

Anacron – /etc/anacrontab File
# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
HOME=/root
LOGNAME=root

# These replace cron's entries
1       5       cron.daily      run-parts --report /etc/cron.daily
7       10      cron.weekly     run-parts --report /etc/cron.weekly
@monthly        15      cron.monthly    run-parts --report /etc/cron.monthly

@daily    10    example.daily   /bin/bash /home/aaronkilik/bin/backup.sh                                                                      

The following is a comparison of cron and anacron to help you understand when to use either of them.

Cron Anacron
It’s a daemon It’s not a daemon
Appropriate for server machines Appropriate for desktop/laptop machines
Enables you to run scheduled jobs every minute Only enables you to run scheduled jobs on daily basis
Doesn’t executed a scheduled job when the machine if off If the machine if off when a scheduled job is due, it will execute a scheduled job when the machine is powered on the next time
Can be used by both normal users and root Can only be used by root unless otherwise (enabled for normal users with specific configs)

The major difference between cron and anacron is that cron works effectively on machines that will run continuously while anacron is intended for machines that will be powered off in a day or week.

If you know any other way, do share with us using the comment form below.

Source

WP2Social Auto Publish Powered By : XYZScripts.com