Linux rsync command

Linux Command Utility [/code]rsync[/code] is a very robust, fast content copy command which can be used within the same linux host and over a connected network between 2 linux hosts. It is a special program which has intelligence in terms of not copying data repetitively if the destination has the same copy as source based on file checksum calculations.

We shall explore some of the practical rsync command features and demonstrate them

Syntax of command

$ rsync [OPTIONS] /source/path/ /dest/path/

Running rsync on the same host?

[vamshi@linuxcent ~]$ rsync -avx newfile.txt /tmp/
sending incremental file list
newfile.txt

sent 133 bytes  received 35 bytes  336.00 bytes/sec
total size is 21  speedup is 0.12

Running rsync between two hosts in a network

$ rsync [OPTIONS] host:/source/path/ /dest/path/

Run rsync in Dry-run mode by using [/code]-n[/code] option

$ rsync -avn Source_host:/source/path Destination_host:/dest/path

This generally runs over the SSH protocol and you are required to enter the login credentials appropriately.

How to invoke SSH remote shell in rsync?

In case you are using a SSH keys then you have to invoke the remote shell to authenticate to the remote server with your private keypair. This is Demonstrated as follows:

$ rsync -avxn --rsh="ssh -i ~/.ssh/vamshi_id_rsa" vamshi@<Your.Source.IP.DNS>:"/<Source_Path>" "/<Destination_Path>"

For more information about the SSH key setup, Please refer to our SSH keys section

How to persist Hard links on the system using rsync. Following is the Demonstration

Flag : -H. Using this option enables to preserve the HardLinks over the destination copy of the data.

$ rsync -avHx /path/to/source/ /path/to/destination/

The most practical example of working with rsync comes in replicating mission critical data or transferring Database dumps within the DB servers etc.,

How to exclude certain directories in rsync in linux ?

using --exclude filter option is demonstrated as follows:

$ rsync -avx /source/path/to/backup-v31/ /dest/databackups/backup-v31/ --exclude="DontTouchMyData/"

Using the delete option, enables us to delete the directories from the source upon completion of the operation.

Note: This operation has the same effects as the mv command on linux but performed over the network between source and destination hosts.

$ rsync -avx --delete /source/path/to/backup-v31/ /dest/databackups/backup-v31/ --exclude="data/" --exclude="data/board" --exclude="cache/apt" --exclude="opt"

Redirect the rsync output to a file by appending output redirection symbol to a file on current location

$rsync -avx --delete /source/path/to/backup-v31/ /dest/databackups/backup-v31/ --exclude="data/" --exclude="data/board" --exclude="cache/apt" --exclude="opt"  >>/tmp/rsync.log

 

How to create user account in Linux

The Linux system provides a couple of command line utilities to create new users on the system

As we are aware, the Linux login has the essential fields listed as follows:

  • A unique system wide username,
  • A Strong password,
  • The home directory and
  • A login shell.

These are the mandatory fields to enable account creation.

The other fields are the UID and GID numbers associated with User an Group name numerical IDs which will be generated sequentially allocated by the Linux Kernel

We can do a broad categorization of login accounts into 2 types, those are the Privileged and the normal user.

The Absolute Privileged account is root which comes by default in all the linux machines.

The normal account can be enabled with root Privileged by assigning user to certain groups and providing elevated access in the scope.

What is the Process to create a User account in Linux?

The user creation has to be done with root privileges using useradd command.

$ sudo useradd newuser

Now it’s time to enter the password

$ sudo passwd newuser

How to check if the userid is present and active on the system?

The new user details will be updated to /etc/passwd file and the login information updated to /etc/shadow

Now let’s check if the user account is created and has a valid shell

vamshi@node03:/$ grep vamshi /etc/passwd

vamshi:x:1001:1001::/home/vamshi:/bin/bash

How to Add the user to new groups in Linux?

Usermod command line linux utility enables to add user to groups and the ability to add an existing user to new groups additionally or overwrite the group membership

$ usermod -aG dockerroot wheel vamshi

The option -a: appends the user to two new groups called dockerroot and wheel with out overwriting the existing user assigned groups, violating this option will restrict the newuser to be part of only the mentioned groups in the command

How to check and verify if the user is a member of group in Linux?

[vamshi@node02 Linux-blog]$ id vamshi
uid=1001(vamshi) gid=1001(vamshi) groups=1001(vamshi),0(root),10(wheel),992(dockerroot)

How to Verify the Login Confirmation in Linux?

From the root user account run the command: su - newuser to check the new login account environment.

How to find the group names assigned to the user

The user can list of his active membership groups by running the linux command groups

The user can run the groups command to list the groups with active membership

[vamshi@linuxcent ~]$ groups
vamshi root wheel dockerroot

Login to the server remotely using SSH

You may now use the ssh command to login with the new username and enter your password at login prompt.

$ ssh vamshi@linuxcent.com

How to connect to server with SSH running on non-standard port like 2202?

[vamshi@linuxcent ~]$ ssh localhost -p 2202
Last login: Mon Mar 13 17:57:56 2020 from 10.100.0.1

How to create a useraccount in Linux using useradd command?

The usercreation can also be done with parametrized command as demonstrated below:

$ sudo useradd vamshi -b /home/ -m -s /bin/bash

Alternatively you can be more elaborate as mentioned below:

$ sudo useradd vamshi -c "Vamshi's user account" -d /home/vamshi -m -s /bin/bash -G dockerroot

The useradd command-utility options describes as follows:

-b or --base-dir : base directory of new user home directory.

-c or --comment : Description about the user Or as A Standard Practice can be used to Mention the Current User’s Full name.

-d or --home-dir : create the user’s home directory

-m or --create-home :  create the user’s home directory as per -d option.

-s or --shell : Type of Login Shell.

-u or --uid : is the Unique UID on linux machine

-G or --groups : list of secondary groups to be assigned

-k or --skel : determines the default parameters if no options are passed while account creation. Present at /etc/default/useradd

With the skel properties finely tunes, you can proceed to use adduser command which is based on the default skel behavior as shown below:

$ sudo adduser vamshi

How to using the SSH key pair to login:
Use the -i followed by the /path/to/id_rsa private key file

$ ssh -i ~/.ssh/id_rsa vamshi@linuxcent.com
$ ssh -i ~/.ssh/id_rsa -l linuxcent.com

-l : using the login name

-i : is the identity file; rsa the private key file

 

Troubleshooting the SSH connection in Verbose mode printing Debug information

Using -v option with the ssh command will print the debug information while logging

The verbosity levels -v can be concatenated from one to Nine; eg -v to -vvvvvvvvv

$ ssh -i ~/.ssh/id_rsa vamshi@linuxcent.com -vvvvvvvvv

How to make a file or Folder undeletable on Linux

How to make a file or Folder/Directory un-deletable on Linux?

The linux operating as we know if famous for the phrase “Everything is a file”, In such circumstances it is interesting to explore the possibilities of making a file undeletable, even by the owner of the file and for that matter even the root user, In the Linux Ecosystem the root is the poweruser.

This section we will see the potential of such feature.

As we have already seen the section on deleting files on Linux (removing the files in Linux).

We will now demonstrate the power of Linux where you can restrict the deletion of a file on Linux.

Linux offers a chattr commandline utility which generally modifies the file attributes as the name suggests, but the practical use is to make a file undeletable.

Sample command syntax:

[vamshi@linuxcent ~]$ chattr +i <samplefile>
vamshi@linuxcent delete-dir]$ sudo chattr +i samplefile2.txt
Now we do ls -l samplefile2.txt
[vamshi@linuxcent ~]$ sudo chattr +i samplefile2.txt
[vamshi@linuxcent ~]$ ls -l samplefile2.txt
-rw-rw-r--. 1 vamshi vamshi 4 Apr 8 15:42 samplefile2.txt

Now we shall try to write some content to this file and see no change in the basic file permissions(see changing ownership of files).

[vamshi@linuxcent delete-dir]$ echo "New content" > samplefile2.txt
-bash: samplefile2.txt: Permission denied

Deleting file forcefully with the --force option ?

[vamshi@linuxcent delete-dir]$ sudo /bin/rm -f samplefile2.txt

/bin/rm: cannot remove ‘samplefile2.txt’: Operation not permitted

Linux command lsattr offers the ability to view the permissions set by the chattr command.
The current File attributes can be listed using lsattr followed by the filename [/code]samplefile2.txt[/code] as below

[vamshi@linuxcent delete-dir]$ lsattr samplefile2.txt
----i----------- samplefile2.txt

Even the root user on the host is unable to delete the file or modify its contents.

The file can be deleted only when the attributes are unset, It is demonstrated as follows:

[vamshi@linuxcent delete-dir]$ sudo chattr -i samplefile2.txt
[vamshi@linuxcent delete-dir]$ lsattr samplefile2.txt
---------------- samplefile2.txt

As we can see the lsattr doesn’t hold true anymore attributes on our file samplefile2.txt and is now being treated as any other normal file with basic file attributes.
The - operation removes the special linux file attributes on the mentioned file.

The chattr / lsattr linux commandline utilities currently supports the popular filesystems such as ext3,ext4,xfs, btrfs etc,.

Linux Find command – with Practical examples

The Linux find command utility is a powerful command in locating the files and directories at system wide level, the

The basic syntax of find command is very straight forward. The number of filters and types of options you choose while forming the find command determines and complexity of the operation and is directly proportional to the run time of the command.

Lets examine the general syntax of Linux find command line utility

$ find [path] [Options/filters] [expression]

How to Find all the files that are modified within 1 day.

$ find . -mtime -1

Use find command to find all the files that are modified within last x Minutes

$ find . -mmin -360

How to Find all the files that are created within given Minutes

$ find . -cmin -360

How to Find all the files under a specific size on the filesystem.

$ find . -type f -size -100G

NOTE: the - will find the files including and under the mentioned size

How to find really big size files with a given size using Linux Find Command.

$ find . -type f -size +100G

NOTE: the + will find the files exceeding the mentioned size

How to Find all the files with a pattern match using Find command?

vamshi.santhapuri@linux-pc:~/Linux/Programs> find *.py
my_program.py
myProgram.py
My_program.py

OutPut Demonstrated:

vamshi@linuxcent:~/Linux/Programs> ls -l
total 0
-rwxr-xr-x 1 vamshi users 0 Apr 8 16:33 my_program.py
-rwxr-xr-x 1 vamshi users 0 Apr 8 16:32 myProgram.py
-rwxr-xr-x 1 vamshi users 0 Apr 8 16:32 My_program.py ex

 

Find Files Based on file-type using option -type

Find only the regular file type

$ sudo find / -type f -print

Find only the Directory

$ sudo find / -type d -print

Lets see some special file formats like character files as in network level files and block files as in storage device file type.

$ sudo find /dev/ -type b -print
/dev/sdb8
/dev/sdb7
/dev/sdb6
/dev/sdb5
/dev/sdb4
/dev/sdb1
/dev/sdb
/dev/sda6
/dev/sda5

How to find empty files and Directories in Linux using Find command?

$ find . -empty # Finds all files and directories that are empty
$ find . -type f -empty #Find onlt empty files
$ find . -type d -empty #Find only empty Directories

How to Find all the hidden files and directories using Find command

You can also add the type flag as required

$ find . -name ".*" //Prints all the files and directories that are hidden

Find the character stream files and identify them yourselves.

$ sudo find / -type c -print

 

How to exclude some files or directories while using the find command?

The negation Operator ! in find command line

[vamshi@linuxcent ~]$ find / -type d  ! -path /mount ! -path /mnt/3TB/

How to find the files with .py extension and then setting the execute permission on them ?

-exec is a special builtin option which takes the specified command on the selected files

[vamshi@linuxcent ~]$ find *.py -exec chmod +x {} \;

A practical example of Finding and Deleting Big size files using Find Command

We Demonstrate a Big thread dump file that we generated in our Test environment by finding it on our server and then deleting it.

[vamshi@linuxcent ~]$ find /var -type f -size +100G -exec rm {} \;

 

To find the files with matching file permissions

[vamshi@linuxcent ~]$ sudo find / -type f -perm 0600 -print

More complex find operations can be performed by combining the negation operator and by excluding the certain mount points and using the logical AND OR operators.

For example:

sudo find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -exec ls -ld {} \;

Ignore case using the find command

The filter -iname enables the find to perform case insesitive search.

[vamshi@node02 Linux-blog]$ find . -iname "rEadMe*" 
./Debian-Distro/README-Debian-Distro
./OpenSuse-Distro/README-Opensuse-Distro
./README
./Redhat-Distro/Centos/README-CentOS
./Redhat-Distro/README-Redhat-Distro

How to use Maxdepth Option in the find command to explore the directory depth?

[vamshi@node02 Linux-blog]$ find . -maxdepth 1 -name "README*" 
./README

By using find command filter option -maxdepth Now we can extract the results based on the one level deeper subdirectory, which is demonstrated as follows:

[vamshi@node02 Linux-blog]$ find . -maxdepth 2 -name "README*" 
./Debian-Distro/README-Debian-Distro
./OpenSuse-Distro/README-Opensuse-Distro
./README
./Redhat-Distro/README-Redhat-Distro

How to use mindepth Option in the find command to restrict the results based on the subdirectory depth?

The -mindepth filter option restricts the find command search to nth subdirectory level from the given path.

[vamshi@node02 Linux-blog]$ find . -mindepth 3 -name "README*" 
./Redhat-Distro/Centos/README-CentOS

 

How to access Tar files in Linux/Unix

The Linux tar command abbreviation is “tar archive” released under POSIX standards initially and It now follows the GNU standards

Often when you download the files from the internet they are in the .tar, tar.gz. Or tar.bz2 compressed format using either bz2 or gz compression algorithm.

If you are familiar with the Opensource then there’s a good chance that you would have come across the extensions like Package-name.tar, tar.gz, tar.bz, tar.xz which are standard.

Well most open source software use tarballs to distribute programs/source codes in this format as it offers efficient compression and better organized way of grouping files.

It supports a vast range of compression programs such as gzip, bzip2, xz, lzip, lzma, lzop.

In the following tutorial we will show how to Compress/Extract the files into tar.gz or tgz.

How to specify the format POSIX Or GNU while using tar Command?

[vamshi@linuxcent ]$ tar --format=posix -cf posix.tar *
[vamshi@linuxcent ]$  tar --format=gnu -cf gnu.tar *
[vamshi@linuxcent ]$  file posix.tar gnu.tar 
posix.tar: POSIX tar archive
gnu.tar: POSIX tar archive (GNU)

GNU is based on an older POSIX format, So that’s why it says POSIX for both.

To print the contents information of an archived directory, use the directory name as a file name argument in conjunction with --list (-t). To find out file attributes, include the --verbose (-v) option.

Firstly start off by long listing ls in the present directory we have here:

vamshi@LinuxCent:~/Linux> ls
Debian-Distro/  OpenSuse-Distro/ README  Redhat-Distro/

We will now compress the present working directory using Linux GNU’s tar command line utility.. Creating a tar of the current directory mentioned by Asterisk *. The Options -c creates, -v: Verbose mode, -z: Uses GZIP algorithm
Demonstration shown below:
Either one of the following commands can be used

vamshi@LinuxCent:~/Linux> tar --gzip -cvf Linux-flavours.tar.gz *
vamshi@LinuxCent:~/Linux> tar -cvzf Linux-flavours.tar.gz *
Debian-Distro/
Debian-Distro/ubuntu.txt
Debian-Distro/debian.txt
Debian-Distro/README-Debian-Distro
Linux-flavours.tar.gz
OpenSuse-Distro/
OpenSuse-Distro/README-Opensuse-Distro
OpenSuse-Distro/opensuse.txt
README
Redhat-Distro/
Redhat-Distro/Fedora/
Redhat-Distro/Fedora/fedora.txt
Redhat-Distro/Centos/
Redhat-Distro/Centos/centos.txt
Redhat-Distro/Centos/CentOS-versions/
Redhat-Distro/Centos/CentOS-versions/centos7.txt
Redhat-Distro/Centos/CentOS-versions/centos5.5.txt
Redhat-Distro/Centos/CentOS-versions/centos6.9.txt
Redhat-Distro/Centos/CentOS-versions/centos5.8.txt
Redhat-Distro/Centos/CentOS-versions/centos6.1.txt
Redhat-Distro/Centos/README-CentOS
Redhat-Distro/README-Redhat-Distro
Redhat-Distro/RHEL-Versions/
Redhat-Distro/RHEL-Versions/redhat5.txt
Redhat-Distro/RHEL-Versions/redhat7.txt
Redhat-Distro/RHEL-Versions/redhat6.txt
Redhat-Distro/RHEL-Versions/redhat8.txt
Redhat-Distro/redhat.txt

How to List/view Archives

The option-t does a Dry-run of extract operation but only to print the contents of the mentioned compression.

vamshi@LinuxCent:~/Linux> tar -tvf Linux-flavours.tar.gz
Debian-Distro/
Debian-Distro/ubuntu.txt
Debian-Distro/debian.txt
Debian-Distro/README-Debian-Distro
…

How to Extracting tar.gz File?

Extracting the tar file using the options -x works out just fine as -x option chooses the tye of decompression based on the compression file type, and the content will be extracted to current working directory.

Here are various extraction options:

$ tar -xvf Linux-flavours.tar.gz
$ tar -zxvf Linux-flavours.tar.gz
$ tar --gzip -xvf Linux-flavours.tar.gz

The Filter / Options for compression types:
-z or --gzip : Used for Archival operation for .gzip type
-j -r --bzip2: Used for archival operation for .bzip2 type
[/code]-J[/code] or --xz: User for Archival for .xz type

How to Extract Only Specific Files from a compressed tar archive (tar) File

This doesn’t require any special option but you have to name the exact file and directory that you want to extract

[vamshi@linuxcent ~]$ tar -zxvf redmine-4.0.6.tar.gz redmine-4.0.6/bin/about
redmine-4.0.6/bin/about

Successful in extracting only the redmine-4.0.6/bin/about file from the redmine-4.0.6.tar.gz archive.

[vamshi@linuxcent ~]$ ls -l redmine-4.0.6/bin/about 
-rwxrwxr-x. 1 vamshi vamshi 167 Dec 20 11:46 redmine-4.0.6/bin/about

How to Extract specific files or Directories from the archive

vamshi@LinuxCent:/tmp/linux-test> tar -zxvf Linux-flavours.tar.gz Redhat-Distro/Centos/
Redhat-Distro/Centos/
Redhat-Distro/Centos/centos.txt
Redhat-Distro/Centos/CentOS-versions/
Redhat-Distro/Centos/CentOS-versions/centos7.txt
Redhat-Distro/Centos/CentOS-versions/centos5.5.txt
Redhat-Distro/Centos/CentOS-versions/centos6.9.txt
Redhat-Distro/Centos/CentOS-versions/centos5.8.txt
Redhat-Distro/Centos/CentOS-versions/centos6.1.txt
Redhat-Distro/Centos/README-CentOS

 

This way we are able to extract only the specific directories pertaining to Centos from Redhat-Distro.
Now we would do the extraction of the contents on Redhat-Distro and its sub directories.
Extracting Sub-directories inside the compressed tar.gz

How to Extract TAR file Contents to a New directory?

The tar program by default, extracts the archive contents to the present working directory.
By specifying the option --directory (-C) You can extract archive files in a Target directory.

vamshi.santhapuri@LinuxCent:/tmp/linux-test1> tar -xzvf ~/Linux/jdk-8u101-linux-x64.tar.gz  -C /usr/local/

The above operation extracts the java bundle to /usr/local/ directory.

How to extract only the specific directory from the Compression to a Target directory?

vamshi.santhapuri@LinuxCent:/tmp/linux-test1> tar -xzvf ~/Linux/Linux-flavours.tar.gz Redhat-Distro/RHEL-Versions/ -C /tmp/linux-test
Redhat-Distro/RHEL-Versions/
Redhat-Distro/RHEL-Versions/redhat5.txt
Redhat-Distro/RHEL-Versions/redhat7.txt
Redhat-Distro/RHEL-Versions/redhat6.txt
Redhat-Distro/RHEL-Versions/redhat8.txt

How to tar compress the specific Files and Directory and Sub-directories / Multiple Directories using tar command?

Below is the Demonstration of compression program using gz compression.

vamshi@LinuxCent:~/Linux> tar -cvzf Redhat-Distro/ Linux-flavours.tar.gz centos.txt fedora.txt opensuse.txt redhat.txt ubuntu.txt
centos.txt
fedora.txt
opensuse.txt
redhat.txt
Redhat-Distro/centos.txt
Redhat-Distro/fedora.txt
Redhat-Distro/redhat.txt
Redhat-Distro/Redhat-Versions/
Redhat-Distro/Redhat-Versions/redhat5.txt
Redhat-Distro/Redhat-Versions/redhat7.txt
Redhat-Distro/Redhat-Versions/redhat6.txt
Redhat-Distro/Redhat-Versions/redhat8.txt

You can also compress multiple directories and files into a single tar.gz file as demonstrated below

How to exclude particular directories and file from the compression using tar command?

We can make use of the --exclude="DontIncludethisPath" in Linux tar command, where in the base directory of mentioned pattern are excluded.. Lets run the tar command and see the results

vamshi@linuxCent:~/Linux/OSes> tar -czvf exclude-flavours.tar.gz --exclude="Redhat-Distro" .
./
./OpenSuse-Distro/
./OpenSuse-Distro/README-Opensuse-Distro
./OpenSuse-Distro/opensuse.txt
./Debian-Distro/
./Debian-Distro/ubuntu.txt
./Debian-Distro/debian.txt
./Debian-Distro/README-Debian-Distro
tar: .: file changed as we read it

The compression successfully completed and now lets list out the files

vamshi@linuxCent:~/Linux/OSes> ls -lthr
total 16K
drwxr-xr-x 2 vamshi users 4.0K Apr  8 14:09 OpenSuse-Distro
drwxr-xr-x 2 vamshi users 4.0K Apr  8 14:09 Debian-Distro
drwxr-xr-x 5 vamshi users 4.0K Apr  8 14:09 Redhat-Distro
-rw-r--r-- 1 vamshi users  718 Apr 8 19:18 exclude-flavours.tar.gz

From the dry-run extract output of the compression does not contain the Directory Redhat-Distro

vamshi@linuxCent:~/Linux/OSes> tar -tvf exclude-flavours.tar.gz
drwxr-xr-x vamshi/users 0 2020-04-08 19:18 ./
drwxr-xr-x vamshi/users 0 2020-04-08 14:09 ./OpenSuse-Distro/
-rw-r--r-- vamshi/users 0 2020-04-08 14:09 ./OpenSuse-Distro/README-Opensuse-Distro
-rw-r--r-- vamshi/users 9 2020-04-08 13:22 ./OpenSuse-Distro/opensuse.txt
drwxr-xr-x vamshi/users 0 2020-04-08 14:09 ./Debian-Distro/
-rw-r--r-- vamshi/users 7 2020-04-08 13:22 ./Debian-Distro/ubuntu.txt
-rw-r--r-- vamshi/users 7 2020-04-08 13:50 ./Debian-Distro/debian.txt
-rw-r--r-- vamshi/users 0 2020-04-08 14:09 ./Debian-Distro/README-Debian-Distro

 

How to create symbolic Link or Softlinks in Linux and differentiate between Softlink vs Hardlink

The concept of Links in Linux/Unix based systems is Unique and gives a very deeper understanding of the Linux working internals at various levels.

The symbolic also known as Soft link is a special type of linking that acts as a pointer to the original file present on the disk.

The Softlink span across different filesystems extensively and widely used during software package installation and configuring

Lets look at the example of java command linking:

[root@node02 ]# which java
/bin/java
[root@linuxcent ]# ls -l /bin/java
lrwxrwxrwx. 1 root root 22 Apr 10 11:52 /bin/java -> /etc/alternatives/java
[root@node02 boot]# ls -l /etc/alternatives/java
lrwxrwxrwx. 1 root root 73 Apr 10 11:52 /etc/alternatives/java -> /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.242.b08-0.el7_7.x86_64/jre/bin/java
[root@linuxcent ]#

If you upgrade java on your system then the /bin/java command points out to a newer installed version of /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.242.b08-0.el7_7.x86_64/jre/bin/java

We will see the demonstration of a Symbolic link.

In Linux to make the links between files, the command-line utility is “ln”.

Softlink Creation syntax using the Linux command line utility ln -s option:

ln -s <source file|Directory > <destination Link file|Directory>

Below is an example

[vamshi@linuxcent html]$ ln -sf /var/www/html/index.html /tmp/index.html

[vamshi@linuxcent html]$ ls -l /tmp/index.html

lrwxrwxrwx. 1 vamshi vamshi 24 Apr  1 18:23 /tmp/index.html -> /var/www/html/index.html

 

The second file is called a symbolic ink to /tmp/index.html

Now the second file /tmp/index.html is called a Symbolic link to the First file on the disk /var/www/html/index.html

It means that the second file is just pointing to the first file’s location on disk without actually copying the contents of the file.

[vamshi@linuxcent html]$ cat /var/www/html/index.html
Welcome to LinuxCent.com
[vamshi@linuxcent html]$ cat /tmp/index.html
Welcome to LinuxCent.com

When you edit either of the file, the contents of the original file on disk are directly modified.

 

How to create Softlinks to Directories in Linux ?
The same logic applies to creating the soft links to directories, Lets see the Demonstration below:

[vamshi@linuxcent html]$  ln -sf /var/www/html/linuxcent/static/ /tmp/static
[vamshi@linuxcent html]$ ls -l /tmp/static
lrwxrwxrwx. 1 vamshi vamshi 32 Apr  8 18:37 /tmp/static -> /var/www/html/linuxcent/static/


 

How do we Remove the linking between the files is even simpler.

Simply run the unlink command on its Destination:

Sample command:

unlink <destination Link file | Directory>

Lets see the Demonstration

unlink /tmp/data-dir

 

Understanding Symbolic / Hard link concept better with improving knowledge on Inode.

To better understand the concept of Symbolic linking we need to understand the concept of Inode numbers present in Linux. I will give a brief overview of it in this section But for Detailed Review, Please see the What is Inode in Linux Section.

We can list out the inode number of any file on linux system using [/code]ls -i <filename>[/code]

Now The extreme left column indicates the system wide unique inode number:

[root@node02 ~]# ls -li /var/www/html/index.html /tmp/index.html 
67290702 lrwxrwxrwx. 1 root root 24 Apr 8 19:09 /tmp/index.html -> /var/www/html/index.html
33557754 -rw-r--r--. 1 root root 25 Apr 8 18:19 /var/www/html/index.html

We can see here the inode number for both the files have different, Because the second file is just a pointer to the original source file..

So why do we create the Symbolic Links ?

We have the advantages of the Softlinks

  1. One Advantage of Softlinks/symbolic links is they span across different filesystems
  2. Can have many softlinks to a single file/Directory.
  3. Can create Symbolic Links of Directories and Files respectively.
  4. Rsync program by default preserves the symbolic links.
  5. The softlinks become activated immediately if the source is recreated or recovered after any kinds of network outages.

What are the best practices when using Softlinks ?

The best practice while creating softlinks is to mention absolute path for source and destination links.

On the other hand you should also understand the disadvantages or shortcomings.

  1. It is Important to observe that If the source file is deleted then the symbolic link becomes useless.
  2. Incases of the Network filesystem issues leading to unavailability of softlinks.

It is also Essential to understand about the Hardlinks to get an overall understanding.

 

Creating a hard link is a simple operation using ln command with no options

Sample Command:

$ ln /path/to/source/ /path/to/HardLink/

So lets start of by creating a hard link of our file /var/www/html/index.html

[vamshi@linuxcent linuxcent]$ ln /var/www/html/index.html /tmp/index-hl.html

The command ls -il lists the inode number of the files.

[vamshi@linuxcent  ]$ ls -i
33557752 index-hl.html  33557752 index.html

So to conclude, The hard linking results in the same inode number, howmany ever times the hardlink of same file is created.
The data continues to persists in the same storage location on the filesystem even if one of the hardlink file is deleted.
As long as the inode number is identical on the files, no filename change matters to the filesystem.
There will be no change in Hardlink behaviour.

Let’s add some content to the hardlink file here and see the Demonstration

[vamshi@linuxcent ]$ echo "We are updating the file to check out the Hardlinks" >>  /tmp/index-hl.html
We are updating the file to check out the Hardlinks

The new line is added in the original file.

[vamshi@linuxcent linuxcent]$ cat index.html
Welcome to LinuxCent.com
We are updating the file to check out the Hardlinks

Content manipulations to either of the files will be treated as a same file.

How to Identify how many times a particular file was linked ?

Note that Linux Command ls -li provides the actual link aggregate count information in the fourth column represented by the number 2 here, which means that it has a second hardlink reference and both the files are interchangeable.
And It should be noted that a file has a link count of 1 by default as it references itself

$ls -li
33557752 -rw-rw-r--. 2 vamshi vamshi 59 Apr  8 19:48 index-hl.html
33557752 -rw-rw-r--. 2 vamshi vamshi 59 Apr  8 19:48 index.html

In case either one of the file is deleted, the other file survives and continues to function properly.

Lets see some hard facts on the Hardlinks.

  1. Hardlinks can’t be created to Directories.
  2. They do not span across filesystems.

How to use grep command in Linux and Unix

The grep command is one of the most essential commands in Unix/Linux ecosystem, It is used to extract match and find the occurrence of string literals and patterns among the text files.

In this section we will focus on the important scenarios and provide the realtime explanation about the Various Grep command options offered in linux command line.

We now have a text file with Following content.

Below is the content of the file called intro.txt.

[vamshi@linuxcent grep]$ cat intro.txt
the first line is in lower case
THE SECOND LINE IS IN UPPER CASE


There following are Most popular Linux server Distributions:
1) Redhat Enterprise Linux
2) Ubuntu
3) Centos
4) Debian
5) SUSE Linux Enterprise Server
This is a Demonstration of Linux grep command

Let’s start with search of a string pattern in the given file

The grep command sample search syntax is

$ grep “string pattern” <filename>
$ cat < filename | * > | grep "string pattern"

Lets see the Demonstration

[vamshi@linuxcent grep]$ grep "Linux" intro.txt
There following are Most popular Linux server Distributions:
1) Redhat Enterprise Linux
5) SUSE Linux Enterprise Server
This is a Demonstration of Linux grep command

Searching for a pattern on multiple files using grep command

Lets see the Demonstration

[vamshi@linuxcent grep]$ grep "Linux" intro.txt intro-demo.txt
intro.txt:There following are Most popular Linux server Distributions:
intro.txt:1) Redhat Enterprise Linux
intro.txt:5) SUSE Linux Enterprise Server
intro.txt:This is a Demonstration of Linux grep command
intro-demo.txt:There following are Most popular Linux server Distributions:
intro-demo.txt:1) Redhat Enterprise Linux
intro-demo.txt:5) SUSE Linux Enterprise Server
intro-demo.txt:This is a Demonstration of Linux grep command

 

How to print the sequence number of matched pattern in file using Grep command in Linux?

Print the sequence number of lines that contain the matched string pattern can be achieved using -n Option:

[vamshi@linuxcent grep]$ grep -n "Linux" intro.txt
4:There following are Most popular Linux server Distributions:
5:1) Redhat Enterprise Linux
9:5) SUSE Linux Enterprise Server
11:This is a Demonstration of Linux grep command

The -b Option prints the subsequent starting offset index of the matching word from the lines within the given filename.

[vamshi@linuxcent grep]$ grep -b "Linux" intro.txt
66:There following are Most popular Linux server Distributions:
127:1) Redhat Enterprise Linux
184:5) SUSE Linux Enterprise Server
217:This is a Demonstration of Linux grep command

So far we have seen only the matching string pattern, but if you want to find the occurance of particular word then use grep -w Option

Lets us see the Demonstration below:

[vamshi@linuxcent grep]$ grep -w "Cent" intro.txt


And As expected here we have not seen any occurrence of the word Cent from the file although the word Centos was present, But it didnt match because we used -w option to match the word Cent.

But when we grep for the Word Linux then we can see the exact occurrence of the word and the matching lines are printed.

[vamshi@linuxcent grep]$ grep -w "Linux" intro.txt
There following are Most popular Linux server Distributions:
1) Redhat Enterprise Linux
5) SUSE Linux Enterprise Server
This is a Demonstration of Linux grep command

This can be used in conjunction with -o prints only completely matched word string pattern.

[vamshi@linuxcent grep]$ grep -w -o "Linux" intro.txt
Linux
Linux
Linux
Linux

How to use the Invert Option in Linux grep command

The -v option prints all the lines not matching the given string pattern.

[vamshi@linuxcent grep]$ grep -v "Linux" intro.txt
the first line is in lower case
THE SECOND LINE IS IN UPPER CASE


2) Ubuntu
3) Centos
4) Debian

 

How to print the names of all the files matching the string pattern using Linux Grep command.

Using the -l Option of grep command will print all the file names containing the matching string pattern/string literal

[vamshi@node02 grep]$ grep -l Linux *
intro-demo.txt
intro.txt

How to get the number of Count Matches using Grep command ?

In Linux Grep command we can use the Option -c to get the total occurance Count of the matching pattern/string

Lets see the Demonstration below

[vamshi@linuxcent grep]$ grep -c "Linux" intro.txt
4

How to Exclude specific Directories while searching with grep command ?

The --exclude-dir="Some Directory name" options skips the contents of the mention directory Lets see the Demonstration:

$ grep -w -E "data" * -R --exclude-dir="backup" --exclude-dir="adb-fastboot" --exclude-dir="IntelliJ-IDEA"

How to use Linux Grep commmand to ignore the case  OR perform Case Insensitive search ?

Linux Grep Command offers the -i to skip the case and perform the search.

[vamshi@linuxcent grep]$ grep -i Cent intro.txt
3)Centos

Lets search for the Work Upper from the file with -i option

[vamshi@linuxcent grep]$ grep Upper -i intro-demo.txt
THE SECOND LINE IS IN UPPER CASE

How to Grep for the lines before and After the pattern occurrence in a file

We can use the below options in Linux Grep command to extract the N number of lines matching the containing pattern before/After from the given file.. Lets look at the Options in detail

Generic Syntax:

grep -<A|B|C> “string pattern” filename*

Lets see the Demonstration as follows:

-A: Prints N number of lines After the pattern match and the line containing the match

[vamshi@linuxcent grep]$  grep -A2 docker /etc/passwd
dockerroot:x:996:992:Docker User:/var/lib/docker:/sbin/nologin
mysql:x:27:27:MariaDB Server:/var/lib/mysql:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin

-B: Prints N number of lines Before the pattern match and the line containing the match

[vamshi@linuxcent grep]$  grep -B2 docker /etc/passwd
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
builduser1:x:1002:1002::/home/builduser1:/bin/bash
dockerroot:x:996:992:Docker User:/var/lib/docker:/sbin/nologin

-C: Prints the line Containing the pattern and the N number of lines Before and After

[vamshi@linuxcent grep]$ grep -C2 docker /etc/passwd
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
builduser1:x:1002:1002::/home/builduser1:/bin/bash
dockerroot:x:996:992:Docker User:/var/lib/docker:/sbin/nologin
mysql:x:27:27:MariaDB Server:/var/lib/mysql:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin

Linux Grep command using the Regular Expression (regex) search pattern

How to use the Special Meta-characters in Grep Command

The Special Meta-Character ^ (caret) symbol to match expression at the start of a line.
Practical examples of grep command using meta-characters are as follows:

[vamshi@linuxcent grep]$ grep ^root /etc/services
rootd           1094/tcp                # ROOTD
rootd           1094/udp                # ROOTD

$ (dollar) symbol to match expression at the end of a line

[vamshi@linuxcent grep]$ grep "bash$" /etc/passwd
root:x:0:0:root:/root:/bin/bash
vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash
vamshi:x:1001:1001::/home/vamshi:/bin/bash
jenkins:x:997:994:Jenkins Automation Server:/var/lib/jenkins:/bin/bash
builduser1:x:1002:1002::/home/builduser1:/bin/bash
linuxcent:x:1003:1004::/home/linuxcent:/bin/bash

Another Bonus regex for evading Empty lines from a text file using the Meta-characters ^ Carat and $ Dollar Symbols.

[vamshi@node02 grep]$ grep -Ev "^$" intro.txt
the first line is in lower case
THE SECOND LINE IS IN UPPER CASE
There following are Most popular Linux server Distributions:
1) Redhat Enterprise Linux
2) Ubuntu
3) Centos
4) Debian
5) SUSE Linux Enterprise Server
This is a Demonstration of Linux grep command

As the result of the above command observed Empty lines in our text file are now excluded with the inverted matching of Empty line pattern expression.

Digit Matching operation using Linux Grep Command

The Grep command Option -P offers the perl-regex pattern matching to perform some of the tricky pattern matching conditions, Lets see the Demonstration.

[vamshi@linuxcent grep]$ grep -P "[\W][\d][\d]/" /etc/services

Now we Demonstrate Numerical pattern matching in the following ways to match the exact occurrence of IPv4 address

[vamshi@linuxcent grep]$ ip a |grep -E "[0-9].[0-9].[0-9].[0-9]"
inet 127.0.0.1/8 scope host lo
inet 10.100.0.20/24 brd 10.100.0.255 scope global noprefixroute eth1

The similar result can be extracted using -P, Demonstrated as below:

[vamshi@linuxcent grep]$ ip a  | grep -P "[\d].[\d].[\d].[\d]"
inet 127.0.0.1/8 scope host lo
inet 10.100.0.20/24 brd 10.100.0.255 scope global noprefixroute eth1

Highlighting the Search patterns with Color codes

If you want to highlight the search pattern from the output we can make use of Color code Option is grep

[vamshi@linuxcent ~]$ ps -ef |grep java --color=yes

 

grep command and the Meta-characters with practical examples

In the Extended Regular Expression the metacharacters ?, \+, \{,  \|, \(, and \) enhances and takes the search string to manifest into a rich pattern

The square brackets [/code][ ][/code] includes a list of characters and it matches a single character in the list. Within the bracket, we can specify a  range, like [a-z] [0-9] [abcd], But it only matches a single character in the give list range.
The brackets can contain the carat ^ or the $ symbols and can be globbed with the wildcard characters for finding the repetitive pattern.

Here we shall see the demonstration of a few metacharacters conjunction into a single grep command

Using the Infix Operator | with the meta-characters

$ dmesg -H | egrep '(s|h)d[a-z]'

A quick practical look at the dmesg to find about the errors and warnings using grep command.

$ dmesg -H | grep -Ei “error|warn”

How to find the exact work match for the word error or err with a blank white space at the start of the word from dmesg?
$ dmesg -H | grep -Ei “(er)[r]{1,2}(or)”
$ dmesg -H | grep -Ei “(\We)[r]+(or)|(\Werr)”

Explanation: The grep search metacharacter regular expression matches the occurring of the string literals “error” with the minimum 1 time occurrence (error) of literal r and maximum 2 times.

The output only prints lines containing the word “error“ in a case insensitive grep search.

 

Another great practical example here we apply the same logic to enhance the metacharacter regex pattern to search for the occurrence of error with but without a trailing colon “:” symbol

dmesg -H | grep -Ei “(error)[:]{0}”

 

Linux Copy File Command for Files and Directories – cp Command Examples

Linux copy files command: cp is generally used for organizing the data on the Linux operating system, It copies the files and directories.

We shall take a deeper look at Linux cp command-utility in the section

In order to copy files and directories, you must have read permissions on the source file(s) and write permissions on the destination directory

How do I copy files under Linux operating systems?

How do I make a 2nd copy of a file on a Linux bash shell?

How can I copies files and directories on a Linux

Linux Copy File command Syntax

cp sourcefile destinationfile
cp sourcefile DESTDIR
cp sourcefile1 sourcefile2 DESTDIR
cp [OPTION] SOURCE DESTFILE
cp [OPTION] SOURCE DESTDIR

How to Copy a Directory if the destination does not exist?

To achieve this we can make use of the following cp command options -R or -r: Copy directories recursively.

Linux cp command Syntax with -R option:

cp -R SOURCE DESTINATION

If the destination doesn’t exist, it will be created.

It can also be used to Copy the contents Recursively

Lets see the demonstration as follows:

[vamshi@linuxcent ]$ cp -R dir1/ dir1-copy
[vamshi@linuxcent ]$ ls -l 
total 0
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:35 dir1
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:37 dir1-Recursive

Using the verbose Option -v to print the copy activity information onto the output screen.

Let’s use the -v flag to print the verbose information onto the screen.

How to Preserve the Source file and Directory permission?

Linux Copy command Syntax with -p option:

-p option preserves the mode, ownership and timestamps from the source to the destination

cp -p file1 file1-copy

Lets us see the Demonstration as Below

[vamshi@node02 cp-command]$ cp -Rp dir1/ dir1-copy
[vamshi@node02 cp-command]$ ls -ld dir1*
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:35 dir1
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:35 dir1-copy
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:37 dir1-Recursive

From the out we can conclude the the Linux copy command with -p Option preserves the original timestamps information and copies it to the destination

Linux cp command with Force copy -f Option, It forcefully overwrites the destination content
Sample Syntax:

cp -f file1 file1-copy

How to Copy Multiple files at once ?

Asterisk / wildcard (*) character is used to copy files multiple files with same pattern.

[vamshi@linuxcent ]$ cp -varpf file* DEST/
‘file10.txt’ -> ‘DEST/file10.txt’
‘file1.txt’ -> ‘DEST/file1.txt’
‘file2.txt’ -> ‘DEST/file2.txt’
‘file3.txt’ -> ‘DEST/file3.txt’
‘file4.txt’ -> ‘DEST/file4.txt’
‘file5.txt’ -> ‘DEST/file5.txt’
‘file6.txt’ -> ‘DEST/file6.txt’
‘file7.txt’ -> ‘DEST/file7.txt’
‘file8.txt’ -> ‘DEST/file8.txt’
‘file9.txt’ -> ‘DEST/file9.txt’

The options -p or -d enables preserving the links and can be used in conjunction with -R option to copy contents Recursively from the source directory.

How to Copy Files and Folders on Linux Using the cp Command recursively to Destination Directory

How to preserve the links with cp command?

Using the Options -p preserves the links and -r Option copies the content recussively same as -R Option and -v prints the verbose information

[vamshi@node02 Linux-blog]$ cp -varpf Redhat-Distro/ /tmp/DEST
‘Redhat-Distro/’ -> ‘/tmp/DEST’
‘Redhat-Distro/Fedora’ -> ‘/tmp/DEST/Fedora’
‘Redhat-Distro/Fedora/fedora.txt’ -> ‘/tmp/DEST/Fedora/fedora.txt’
‘Redhat-Distro/Centos’ -> ‘/tmp/DEST/Centos’
‘Redhat-Distro/Centos/centos.txt’ -> ‘/tmp/DEST/Centos/centos.txt’
‘Redhat-Distro/Centos/CentOS-versions’ -> ‘/tmp/DEST/Centos/CentOS-versions’
‘Redhat-Distro/Centos/CentOS-versions/centos7.txt’ -> ‘/tmp/DEST/Centos/CentOS-versions/centos7.txt’
‘Redhat-Distro/Centos/CentOS-versions/centos6.1.txt’ -> ‘/tmp/DEST/Centos/CentOS-versions/centos6.1.txt’
‘Redhat-Distro/Centos/README-CentOS’ -> ‘/tmp/DEST/Centos/README-CentOS’
‘Redhat-Distro/README-Redhat-Distro’ -> ‘/tmp/DEST/README-Redhat-Distro’
‘Redhat-Distro/RHEL-Versions’ -> ‘/tmp/DEST/RHEL-Versions’
‘Redhat-Distro/RHEL-Versions/redhat5.txt’ -> ‘/tmp/DEST/RHEL-Versions/redhat5.txt’
‘Redhat-Distro/RHEL-Versions/redhat8.txt’ -> ‘/tmp/DEST/RHEL-Versions/redhat8.txt’
‘Redhat-Distro/redhat.txt’ -> ‘/tmp/DEST/redhat.txt’

How to make a symbolic link with Linux cp command to files ?

As we know that ln command us useful to create symboic links, But the Linux copy command Syntax can do that to files with -s Option which creates Symbolic links:

cp -s SOURCE DESTINATION

Linux copy command Syntax with Softlink with Demonstration:

[vamshi@linuxcent ~]$ ls -l total 0
-rw-rw-r--. 1 vamshi vamshi 0 Apr 11 06:39 file1.txt

lrwxrwxrwx. 1 vamshi vamshi 9 Apr 11 06:39 file2.txt -> file1.txt

Linux cp command with interactive prompt using -i option

Sample Syntax:

cp -i file1 file1-copy

Also you can make it a best practice to setup alias alias for cp command.
The best practice is enable options -av

cp -av SOURCE DESTINATION
export cp="cp -av"

How can i copy the hidden files ?

To Copy the hidden files we can use cp command with -a option,lets us see in a practical example.

$ cp -av source/ destination/
‘source/.config1’ -> ‘destination/source/.config1’
‘source/.config2’ -> ‘destination/source/.config2’
‘source/.config3’ -> ‘destination/source/.config3’

Generally the hidden files in Linux are prefixed with a dot . So we can also use the wildcard character *, and copy them, below is another pracctical example

[vamshi@linuxcent cp-command]$ cp -av source/.conf* destination/
‘source/.config1’ -> ‘destination/.config1’
‘source/.config2’ -> ‘destination/.config2’
‘source/.config3’ -> ‘destination/.config3’

How to Copy a File from One Location to Another With a Different Name on Linux Using the cp Command

Assuming we have a couple of users on our linux server called Alice and Bob

[alice@linuxcent ~]$ sudo cp -avrpf /home/alice/djangoproject1/ /home/bob/
‘djangoproject1/’ -> ‘/home/bob/djangoproject1’
‘djangoproject1/__init__.py’ -> ‘/home/bob/djangoproject1/__init__.py’
‘djangoproject1/asgi.py’ -> ‘/home/bob/djangoproject1/asgi.py’
‘djangoproject1/settings.py’ -> ‘/home/bob/djangoproject1/settings.py’
‘djangoproject1/urls.py’ -> ‘/home/bob/djangoproject1/urls.py’
‘djangoproject1/wsgi.py’ -> ‘/home/bob/djangoproject1/wsgi.py’
‘djangoproject1/__pycache__’ -> ‘/home/bob/djangoproject1/__pycache__’
‘djangoproject1/__pycache__/__init__.cpython-36.pyc’ -> ‘/home/bob/djangoproject1/__pycache__/__init__.cpython-36.pyc’
‘djangoproject1/__pycache__/settings.cpython-36.pyc’ -> ‘/home/bob/djangoproject1/__pycache__/settings.cpython-36.pyc’

How to backup files using cp command?

The linux cp command offer the option --backup to backup the data files, below is the command.

cp --backup source destination