How to Find Out Who is Using a File in Linux

In this article, we will explain how to find out who is using a particular file in Linux. This will help you know the system user or process that is using an open file.

We can use the lsof command to know if someone is using a file, and if they are, who. It reads kernel memory in its search for open files and helps you list all open files. In this case, an open file may be a regular file, a directory, a block special file, a character special file, a stream, a network file and many others – because in Linux everything is a file.

Lsof is used on a file system to identify who is using any files on that file system. You can run lsof command on Linux filesystem and the output identifies the owner and process information for processes using the file as shown in the following output.

$ lsof /dev/null
List of All Opened Files in Linux
COMMAND    PID    USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
systemd   1480 tecmint    0r   CHR    1,3      0t0    6 /dev/null
sh        1501 tecmint    0r   CHR    1,3      0t0    6 /dev/null
sh        1501 tecmint    1w   CHR    1,3      0t0    6 /dev/null
dbus-daem 1530 tecmint    0u   CHR    1,3      0t0    6 /dev/null
xfce4-ses 1603 tecmint    0r   CHR    1,3      0t0    6 /dev/null
xfce4-ses 1603 tecmint    1w   CHR    1,3      0t0    6 /dev/null
at-spi-bu 1604 tecmint    0r   CHR    1,3      0t0    6 /dev/null
dbus-daem 1609 tecmint    0u   CHR    1,3      0t0    6 /dev/null
at-spi2-r 1611 tecmint    0u   CHR    1,3      0t0    6 /dev/null
xfconfd   1615 tecmint    0u   CHR    1,3      0t0    6 /dev/null
xfwm4     1624 tecmint    0r   CHR    1,3      0t0    6 /dev/null
xfwm4     1624 tecmint    1w   CHR    1,3      0t0    6 /dev/null
xfce4-pan 1628 tecmint    0r   CHR    1,3      0t0    6 /dev/null
xfce4-pan 1628 tecmint    1w   CHR    1,3      0t0    6 /dev/null
Thunar    1630 tecmint    0r   CHR    1,3      0t0    6 /dev/null
Thunar    1630 tecmint    1w   CHR    1,3      0t0    6 /dev/null
xfdesktop 1632 tecmint    0r   CHR    1,3      0t0    6 /dev/null
xfdesktop 1632 tecmint    1w   CHR    1,3      0t0    6 /dev/null
....

To list user specific opened files, run the following command replace tecmint with the actual user name.

$ lsof -u tecmint
List of Files Opened by User
COMMAND    PID    USER   FD      TYPE             DEVICE  SIZE/OFF       NODE NAME
systemd   1480 tecmint  cwd       DIR                8,3      4096          2 /
systemd   1480 tecmint  rtd       DIR                8,3      4096          2 /
systemd   1480 tecmint  txt       REG                8,3   1595792    3147496 /lib/systemd/systemd
systemd   1480 tecmint  mem       REG                8,3   1700792    3150525 /lib/x86_64-linux-gnu/libm-2.27.so
systemd   1480 tecmint  mem       REG                8,3    121016    3146329 /lib/x86_64-linux-gnu/libudev.so.1.6.9
systemd   1480 tecmint  mem       REG                8,3     84032    3150503 /lib/x86_64-linux-gnu/libgpg-error.so.0.22.0
systemd   1480 tecmint  mem       REG                8,3     43304    3150514 /lib/x86_64-linux-gnu/libjson-c.so.3.0.1
systemd   1480 tecmint  mem       REG                8,3     34872    2497970 /usr/lib/x86_64-linux-gnu/libargon2.so.0
systemd   1480 tecmint  mem       REG                8,3    432640    3150484 /lib/x86_64-linux-gnu/libdevmapper.so.1.02.1
systemd   1480 tecmint  mem       REG                8,3     18680    3150450 /lib/x86_64-linux-gnu/libattr.so.1.1.0
systemd   1480 tecmint  mem       REG                8,3     18712    3150465 /lib/x86_64-linux-gnu/libcap-ng.so.0.0.0
systemd   1480 tecmint  mem       REG                8,3     27112    3150489 /lib/x86_64-linux-gnu/libuuid.so.1.3.0
systemd   1480 tecmint  mem       REG                8,3     14560    3150485 /lib/x86_64-linux-gnu/libdl-2.27.so
...

Another important use of lsof is to find out the process listening on a specific port. For example identify the process listening on port 80 using the following command.

$ sudo lsof -i TCP:80
Find Out Process Listening Port
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
httpd    903   root    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   1320 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   1481 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   1482 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   1493 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   1763 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   2027 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   2029 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   2044 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   3199 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   3201 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)

Note: Since lsof reads kernel memory in its search for open files, rapid changes in kernel memory may result into unpredictable outputs. This is one of the major downsides of using lsof command.

For more information, look at the lsof man page:

$ man lsof

That’s all! In this article, we have explained how to know who is using a particular file in Linux. We have shown how to identify the owner and process information for processes using an open file. Use the feedback form below to reach us for any questions or comments.

Source

10 Useful Linux Command Line Tricks for Newbies

I remember when I first started using Linux and I was used to the graphical interface of Windows, I truly hated the Linux terminal. Back then I was finding the commands hard to remember and proper use of each one of them. With time I realised the beauty, flexibility and usability of the Linux terminal and to be honest a day doesn’t pass without using. Today, I would like to share some useful tricks and tips for Linux new comers to ease their transition to Linux or simply help them learn something new (hopefully).

10 Linux Commandline Tricks for Newbies

10 Linux Commandline Tricks – Part 2

  1. 5 Interesting Command Line Tips and Tricks in Linux – Part 1
  2. 5 Useful Commands to Manage Linux File Types – Part 3

This article intends to show you some useful tricks how to use the Linux terminal like a pro with minimum amount of skills. All you need is a Linux terminal and some free time to test these commands.

1. Find the right command

Executing the right command can be vital for your system. However in Linux there are so many different command lines that they are often hard to remember. So how do you search for the right command you need? The answer is apropos. All you need to run is:

# apropos <description>

Where you should change the “description” with the actual description of the command you are looking for. Here is a good example:

# apropos "list directory"

dir (1) - list directory contents
ls (1) - list directory contents
ntfsls (8) - list directory contents on an NTFS filesystem
vdir (1) - list directory contents

On the left you can see the commands and on the right their description.

2. Execute Previous Command

Many times you will need to execute the same command over and over again. While you can repeatedly press the Up key on your keyboard, you can use the history command instead. This command will list all commands you entered since you launched the terminal:

# history

    1  fdisk -l
    2  apt-get install gnome-paint
    3  hostname tecmint.com
    4  hostnamectl tecmint.com
    5  man hostnamectl 
    6  hostnamectl --set-hostname tecmint.com
    7  hostnamectl -set-hostname tecmint.com
    8  hostnamectl set-hostname tecmint.com
    9  mount -t "ntfs" -o
   10  fdisk -l
   11  mount -t ntfs-3g /dev/sda5 /mnt
   12  mount -t rw ntfs-3g /dev/sda5 /mnt
   13  mount -t -rw ntfs-3g /dev/sda5 /mnt
   14  mount -t ntfs-3g /dev/sda5 /mnt
   15  mount man
   16  man mount
   17  mount -t -o ntfs-3g /dev/sda5 /mnt
   18  mount -o ntfs-3g /dev/sda5 /mnt
   19  mount -ro ntfs-3g /dev/sda5 /mnt
   20  cd /mnt
   ...

As you will see from the output above, you will receive a list of all commands that you have ran. On each line you have number indicating the row in which you have entered the command. You can recall that command by using:

!#

Where # should be changed with the actual number of the command. For better understanding, see the below example:

!501

Is equivalent to:

# history

3. Use midnight Commander

If you are not used to using commands such cdcpmvrm than you can use the midnight command. It is an easy to use visual shell in which you can also use mouse:

Midnight Commander in Action

Midnight Commander in Action

Thanks to the F1 – F12 keys, you can easy perform different tasks. Simply check the legend at the bottom. To select a file or folder click the “Insert” button.

In short the midnight command is called “mc“. To install mc on your system simply run:

$ sudo apt-get install mc        [On Debian based systems]
# yum install mc                 [On Fedora based systems]

Here is a simple example of using midnight commander. Open mc by simply typing:

# mc

Now use the TAB button to switch between windows – left and right. I have a LibreOffice file that I will move to “Software” folder:

Midnight Commander Move Files

Midnight Commander Move Files

To move the file in the new directory press F6 button on your keyboard. MC will now ask you for confirmation:

Move Files to New Directory

Move Files to New Directory

Once confirmed, the file will be moved in the new destination directory.

Read MoreHow to Use Midnight Commander File Manager in Linux

4. Shutdown Computer at Specific Time

Sometimes you will need to shutdown your computer some hours after your work hours have ended. You can configure your computer to shut down at specific time by using:

$ sudo shutdown 21:00

This will tell your computer to shut down at the specific time you have provided. You can also tell the system to shutdown after specific amount of minutes:

$ sudo shutdown +15

That way the system will shut down in 15 minutes.

5. Show Information about Known Users

You can use a simple command to list your Linux system users and some basic information about them. Simply use:

# lslogins

This should bring you the following output:

UID USER PWD-LOCK PWD-DENY LAST-LOGIN GECOS
0 root 0 0 Apr29/11:35 root
1 bin 0 1 bin
2 daemon 0 1 daemon
3 adm 0 1 adm
4 lp 0 1 lp
5 sync 0 1 sync
6 shutdown 0 1 Jul19/10:04 shutdown
7 halt 0 1 halt
8 mail 0 1 mail
10 uucp 0 1 uucp
11 operator 0 1 operator
12 games 0 1 games
13 gopher 0 1 gopher
14 ftp 0 1 FTP User
23 squid 0 1
25 named 0 1 Named
27 mysql 0 1 MySQL Server
47 mailnull 0 1
48 apache 0 1 Apache
...

6. Search for Files

Searching for files can sometimes be not as easy as you think. A good example for searching for files is:

# find /home/user -type f

This command will search for all files located in /home/user. The find command is extremely powerful one and you can pass more options to it to make your search even more detailed. If you want to search for files larger than given size, you can use:

# find . -type f -size 10M

The above command will search from current directory for all files that are larger than 10 MB. Make sure not to run the command from the root directory of your Linux system as this may cause high I/O on your machine.

One of the most frequently used combinations that I use find with is “exec” option, which basically allows you to run some actions on the results of the find command.

For example, lets say that we want to find all files in a directory and change their permissions. This can be easily done with:

# find /home/user/files/ -type f -exec chmod 644 {} \;

The above command will search for all files in the specified directory recursively and will executed chmodcommand on the found files. I am sure you will find many more uses on this command in future, for now read 35 Examples of Linux ‘find’ Command and Usage.

7. Build Directory Trees with one Command

You probably know that you can create new directories by using the mkdir command. So if you want to create a new folder you will run something like this:

# mkdir new_folder

But what, if you want to create 5 subfolders within that folder? Running mkdir 5 times in a row is not a good solution. Instead you can use -p option like that:

# mkdir -p new_folder/{folder_1,folder_2,folder_3,folder_4,folder_5}

In the end you should have 5 folders located in new_folder:

# ls new_folder/

folder_1 folder_2 folder_3 folder_4 folder_5

8. Copy File into Multiple Directories

File copying is usually performed with the cp command. Copying a file usually looks like this:

# cp /path-to-file/my_file.txt /path-to-new-directory/

Now imagine that you need to copy that file in multiple directories:

# cp /home/user/my_file.txt /home/user/1
# cp /home/user/my_file.txt /home/user/2
# cp /home/user/my_file.txt /home/user/3

This is a bit absurd. Instead you can solve the problem with a simple one line command:

# echo /home/user/1/ /home/user/2/ /home/user/3/ | xargs -n 1  cp /home/user/my_file.txt

9. Deleting Larger Files

Sometimes files can grow extremely large. I have seen cases where a single log file went over 250 GB large due to poor administrating skills. Removing the file with rm utility might not be sufficient in such cases due to the fact that there is extremely large amount of data that needs to be removed. The operation will be a “heavy” one and should be avoided. Instead, you can go with a really simple solution:

# > /path-to-file/huge_file.log

Where of course you will need to change the path and the file names with the exact ones to match your case. The above command will simply write an empty output to the file. In more simpler words it will empty the file without causing high I/O on your system.

10. Run Same Command on Multiple Linux Servers

Recently one of our readers asked in our LinuxSay forum, how to execute single command to multiple Linux boxes at once using SSH. He had his machines IP addresses looking like this:

10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4
10.0.0.5

So here is a simple solution of this issue. Collect the IP addresses of the servers in a one file called list.txt one under other just as shown above. Then you can run:

# for in $i(cat list.txt); do ssh user@$i 'bash command'; done

In the above example you will need to change “user” with the actual user with which you will be logging and “bash command” with the actual bash command you wish to execute. The method is better working when you are using passwordless authentication with SSH key to your machines as that way you will not need to enter the password for your user over and over again.

Note that you may need to pass some additional parameters to the SSH command depending on your Linux boxes setup.

Conclusion

The above examples are really simple ones and I hope they have helped you to find some of the beauty of Linux and how you can easily perform different operations that can take much more time on other operating systems.

Source

5 Ways to Keep Remote SSH Sessions and Processes Running After Disconnection

SSH or Secure Shell in simple terms is a way by which a person can remotely access another user on other system but only in command line i.e. non-GUI mode. In more technical terms, when we ssh on to other user on some other system and run commands on that machine, it actually creates a pseudo-terminal and attaches it to the login shell of the user logged in.

Keep SSH Sessions Running After Disconnection

5 Ways to Keep SSH Sessions Running After Disconnection

When we log out of the session or the session times out after being idle for quite some time, the SIGHUP signal is send to the pseudo-terminal and all the jobs that have been run on that terminal, even the jobs that have their parent jobs being initiated on the pseudo-terminal are also sent the SIGHUP signal and are forced to terminate.

Don’t Miss: 5 Useful Practices to Keep SSH Server Secure and Protected

Only the jobs that have been configured to ignore this signal are the ones that survive the session termination. On Linux systems, we can have many ways to make these jobs running on the remote server or any machine even after user logout and session termination.

Understand Processes on Linux

Normal Process

Normal processes are those which have life span of a session. They are started during the session as foreground processes and end up in certain time span or when the session gets logged out. These processes have their owner as any of the valid user of the system, including root.

Orphan Process

Orphan processes are those which initially had a parent which created the process but after some time, the parent process unintentionally died or crashed, making init to be the parent of that process. Such processes have init as their immediate parent which waits on these processes until they die or end up.

Daemon Process

These are some intentionally orphaned processes, such processes which are intentionally left running on the system are termed as daemon or intentionally orphaned processes. They are usually long-running processes which are once initiated and then detached from any controlling terminal so that they can run in background till they do not get completed, or end up throwing an error. Parent of such processes intentionally dies making child execute in background.

Techniques to Keep SSH Session Running After Disconnection

There can be various ways to leave ssh sessions running after disconnection as described below:

1. Using screen Command to Keep SSH Sessions Running

screen is a text Window Manager for Linux which allows user to manage multiple terminal sessions at same time, switching between sessions, session logging for the running sessions on screen, and even resuming the session at any time we desire without worrying about the session being logged out or terminal being closed.

screen sessions can be started and then detached from the controlling terminal leaving them running in background and then be resumed at any time and even at any place. Just you need to start your session on the screen and when you want, detach it from pseudo-terminal (or the controlling terminal) and logout. When you feel, you can re-login and resume the session.

Starting a screen Session

After typing ‘screen’ command, you will be in a new screen session, within this session you can create new windows, traverse between windows, lock the screen, and do many more stuff which you can do on a normal terminal.

$ screen

Starting Screen Session in Linux

Starting Screen Session in Linux

Once screen session started, you can run any command and keep the session running by detaching the session.

Run Commands in Screen Session

Run Commands in Screen Session

Detaching a Screen

Just when you want to log out of the remote session, but you want to keep the session you created on that machine alive, then just what you need to do is detach the screen from the terminal so that it has no controlling terminal left. After doing this, you can safely logout.

To detach a screen from the remote terminal, just press “Ctrl+a” immediately followed by “d” and you will be back to the terminal seeing the message that the Screen is detached. Now you can safely logout and your session will be left alive.

Detaching Linux Screen Session

Detaching Linux Screen Session

Resuming Detached Screen Session

If you want to Resume a detached screen session which you left before logging out, just re-login to remote terminal again and type “screen -r” in case if only one screen is opened, and if multiple screen sessions are opened run “screen -r <pid.tty.host>”.

$ screen -r
$ screen -r <pid.tty.host>

Resume Detached Screen Session

Resume Detached Screen Session

To Learn more about screen command and how to use it just follow the link: Use screen Command to Manage Linux Terminal Sessions

2. Using Tmux (Terminal Multiplexer) to Keep SSH Sessions Running

Tmux is another software which is created to be a replacement for screen. It has most of the capabilities of screen, with few additional capabilities which make it more powerful than screen.

It allows, apart from all options offered by screen, splitting panes horizontally or vertically between multiple windows, resizing window panes, session activity monitoring, scripting using command line mode etc. Due to these features of tmux, it has been enjoying wide adoption by nearly all Unix distributions and even it has been included in the base system of OpenBSD.

Start a Tmux Session

After doing ssh on the remote host and typing tmux, you will enter into a new session with a new window opening in front of you, wherein you can do anything you do on a normal terminal.

$ tmux

Start tmux Terminal Session

Start tmux Terminal Session

After performing your operations on the terminal, you can detach that session from the controlling terminal so that it goes into background and you can safely logout.

Perform Linux Commands in Tmux Session

Perform Linux Commands in Tmux Session

Detach Tmux Session from Terminal

Either you can run “tmux detach” on running tmux session or you can use the shortcut (Ctrl+b then d). After this your current session will be detached and you will come back to your terminal from where you can log out safely.

$ tmux detach

Detach Tmux Session in Linux

Detach Tmux Session in Linux

Resuming the Closed Tmux Session

To re-open the session which you detached and left as is when you logged out of the system, just re-login to the remote machine and type “tmux attach” to reattach to the closed session and it will be still be there and running.

$ tmux attach

Resume Tmux Closed Session

Resume Tmux Closed Session

To Learn more about tmux and how to use it just follow the link: Use Tmux Terminal Multiplexer to Manage Multiple Linux Terminals.

3. Using nohup command to Keep Running SSH Sessions

If you are not that familiar with screen or tmux, you can use nohup and send your long running command to background so that you can continue while the command will keep on executing in background. After that you can safely log out.

With nohup command we tell the process to ignore the SIGHUP signal which is sent by ssh session on termination, thus making the command persist even after session logout. On session logout the command is detched from controlling terminal and keeps on running in background as daemon process.

Executing command using nohup in background

Here, is a simple scenario wherein, we have run find command to search for files in background on ssh session using nohup, after which the task was sent to background with prompt returning immediately giving PID and job ID of the process ([JOBID] PID).

# nohup find / -type f $gt; files_in_system.out 2>1 &

Run Linux Command in Background

Run Linux Command in Background

Resuming the session to view if job is still running

When you re-login again, you can check the status of command, bring it back to foreground using 'fg %JOBID' to monitor its progress and so on. Below, the output shows that the job was completed as it doesn’t show on re-login, and has given the output which is displayed.

# fg %JOBID

Run Linux Command in Background

Run Linux Command in Background

4. Using disown Command to Keep SSH Sessions Running

Another elegant way of letting your command or a single task run in background and remain alive even after session logout or disconnection is by using disown.

Disown, removes the job from the process job list of the system, so the process is shielded from being killed during session disconnection as it won’t receive SIGHUP by the shell when you logout.

Disadvantage of this method is that, it should be used only for the jobs that do not need any input from the stdinand neither need to write to stdout, unless you specifically redirect jobs input and output, because when job will try to interact with stdin or stdout, it will halt.

Executing command using disown in background

Below, we sent ping command to background so that ut keeps on running and gets removed from job list. As seen, the job was first suspended, after which it was still in the job list as Process ID: 15368.

$ ping tecmint.com > pingout &
$ jobs -l
$ diswon -h %1
$ ps -ef | grep ping

Run Linux Commands Using Disown

Run Linux Commands Using Disown

After that disown signal was passed to the job, and it was removed from job list, though was still running in background. The job would still be running when you would re-login to the remote server as seen below.

$ ps -ef | grep ping

Verify Job Status

Verify Job Status

5. Using setsid Command to Put SSH Sessions Running

Another utility to achieve the required behavior is setsidNohup has a disadvantage in the sense that the process group of the process remains the same so the process running with nohup is vulnerable to any signal sent to the whole process group (like Ctrl + C).

setsid on other hand allocates a new process group to the process being executed and hence, the process created is totally in a newly allocated process group and can execute safely without fear of being killed even after session logout.

Execute any command using setsid

Here, it shows that the process ‘sleep 10m’ has been detached from the controlling terminal, since the time it has been created.

$ setsid sleep 10m
$ ps -ef | grep sleep

Run Linux Command Using Setsid

Run Linux Command Using Setsid

Now, when you would re-login the session, you will still find this process running.

$ ps -ef | grep [s]leep

Linux Process Running Background

Linux Process Running Background

Conclusion

What ways you could think of to keep your process running even after you logout from SSH session? If there is any other and efficient way you can think of, do mention in your comments.

Source

PacVim – A Game That Teaches You Vim Commands

Although Vim (short for VI Improved) is a popular text editor on Linux systems, people still find it hard to learn, it has a steep learning curve especially the advanced features; a lot of Linux newbies are literally afraid of learning this powerful and highly recommended text editor.

On the other hand, so much effort has been directed by the Tecmint and Linux community towards making Vimeasy to learn; from creating Vim tutorials, sharing useful Vim usage tricks and tips, to developing interactive learning web-apps and command-line games such as PacVim.

PacVim is a free open source, text-based game that teaches you vim commands in a simple and fun manner. It is inspired by the popular and classic PacMan game, and runs on Linux and MacOSX. It helps you to comprehensively learn vim commands in an enjoyable way. Its objective is more or less like that of PacMan – you must move the pacman (the green cursor) over all the characters on the screen while avoiding the ghosts (red G).

How to Install PacVim Game in Linux

To install PacVim game, you need to first install required Curses (graphics library) package on your Linux distribution using default package manager as shown.

$ sudo apt install libncurses5-dev libncursesw5-dev  [On Ubuntu/Debian]
# yum install ncurses-devel                          [On CentOS/RHEL]
# dnf install ncurses-devel                          [On Fedora]

Next, download PacVim source files by cloning its repository and install it as shown.

$ cd ~/Downloads
$ git clone https://github.com/jmoon018/PacVim.git
$ cd PacVim
$ sudo make install

After installing PacVim, you can start learning vim commands by running it from level 0 and the default mode is hard.

$ pacvim

PacVIM Game for Learning Vim Commands

PacVIM Game for Learning Vim Commands

Here are a few keys to move the cursor:

  • h – move left
  • i – move right
  • j – move down
  • k – move up
  • q – quit the game

You can launch it in a specific level and mode (n and h for normal/hard respectively), for example.

$ pacvim n
OR
$ pacvim 2
OR
$ pacvim 2 n

You can find more information including key-usage combinations and how to create your custom maps from the PacVim Github repository.

Read AlsonSnake – Play Old Classic Snake Game in Linux Terminal

That’s all! PacVim is a useful game that teaches you vim commands while having fun with Linux terminal. Use the comment form below to share your thoughts or ask questions about it.

Source

7 Ways to Determine the File System Type in Linux (Ext2, Ext3 or Ext4)

A file system is the way in which files are named, stored, retrieved as well as updated on a storage disk or partition; the way files are organized on the disk.

A file system is divided in two segments called: User Data and Metadata (file name, time it was created, modified time, it’s size and location in the directory hierarchy etc).

In this guide, we will explain seven ways to identify your Linux file system type such as Ext2, Ext3, Ext4, BtrFS, GlusterFS plus many more.

1. Using df Command

df command reports file system disk space usage, to include the file system type on a particular disk partition, use the -T flag as below:

$ df -Th
OR
$ df -Th | grep "^/dev"

df Command - Find Filesystem Type

df Command – Find Filesystem Type

For a comprehensive guide for df command usage go through our articles:

  1. 12 Useful “df” Commands to Check Disk Space in Linux
  2. Pydf – An Alternative ‘df’ Command That Shows Disk Usage in Colours

2. Using fsck Command

fsck is used to check and optionally repair Linux file systems, it can also print the file system type on specified disk partitions.

The flag -N disables checking of file system for errors, it just shows what would be done (but all we need is the file system type):

$ fsck -N /dev/sda3
$ fsck -N /dev/sdb1

fsck - Print Linux Filesystem Type

fsck – Print Linux Filesystem Type

3. Using lsblk Command

lsblk displays block devices, when used with the -f option, it prints file system type on partitions as well:

$ lsblk -f

lsblk - Shows Linux Filesystem Type

lsblk – Shows Linux Filesystem Type

4. Using mount Command

mount command is used to mount a file system in Linux, it can also be used to mount an ISO imagemount remote Linux filesystem and so much more.

When run without any arguments, it prints info about disk partitions including the file system type as below:

$ mount | grep "^/dev"

Mount - Show Filesystem Type in Linux

Mount – Show Filesystem Type in Linux

5. Using blkid Command

blkid command is used to find or print block device properties, simply specify the disk partition as an argument like so:

$ blkid /dev/sda3

blkid - Find Filesystem Type

blkid – Find Filesystem Type

6. Using file Command

file command identifies file type, the -s flag enables reading of block or character files and -L enables following of symlinks:

$ sudo file -sL /dev/sda3

file - Identifies Filesystem Type

file – Identifies Filesystem Type

7. Using fstab File

The /etc/fstab is a static file system info (such as mount point, file system type, mount options etc) file:

$ cat /etc/fstab

Fstab - Shows Linux Filesystem Type

Fstab – Shows Linux Filesystem Type

That’s it! In this guide, we explained seven ways to identify your Linux file system type. Do you know of any method not mentioned here? Share it with us in the comments.

Source

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

WP2Social Auto Publish Powered By : XYZScripts.com