Commands https://www.linuxtechi.com Sun, 30 Jul 2023 07:14:39 +0000 en-US hourly 1 https://www.linuxtechi.com/wp-content/uploads/2020/02/cropped-linuxtechi-favicon-32x32.png Commands https://www.linuxtechi.com 32 32 26 Useful find Command Examples in Linux https://www.linuxtechi.com/find-command-examples-in-linux/ https://www.linuxtechi.com/find-command-examples-in-linux/#comments Sun, 30 Oct 2022 05:51:33 +0000 https://www.linuxtechi.com/?p=5647 Linux is renowned for its vast array of powerful command-line utilities, and the find command stands out as a versatile tool for searching files and directories based on various criteria. Whether you are a seasoned Linux user or a curious beginner, mastering the find command ... Read more

The post 26 Useful find Command Examples in Linux first appeared on LinuxTechi.]]>
Linux is renowned for its vast array of powerful command-line utilities, and the find command stands out as a versatile tool for searching files and directories based on various criteria. Whether you are a seasoned Linux user or a curious beginner, mastering the find command will significantly boost your productivity and efficiency.

In this article, we will explore 26 useful find command examples to unleash its full potential for file search in Linux.

Syntax

$ find <path> {file-or-directory-name} <options> <action-on-result>

Actions on find command result can be

  • – delete :  Delete files or directories
  • -exec command {}\;  : Run the command on the result obtained from find command
  • -ok command : It will run command same as -exec but it will prompt before the actual execution.

Without any further delay let’s jump into find command examples,

1) Search all Files and Directories

To search for directories in current working folder, employ the -type d flag.

$ find . -type d

To search all the files only & not directories, run

$ find . -type f

2) Lists all the files of Specific Directory

Let’s suppose we want to list all files and directories of /home/linuxtechi/Downloads folder, run

$ find /home/linuxtechi/Downloads

Print only files, run

$ find /home/linuxtechi/Downloads -type f

Run following command to print only directories,

$ find /home/linuxtechi/Downloads -type d

output of above commands,

find-files-directories-particular-folder-linux

3) Searching File with Name

The most straightforward use of find is to search for files by name. The following command will find all files named “cleanup.sh” within the current directory and its sub-directories.

$ sudo find /home -type f -name cleanup.sh

Above command will look for cleanup.sh file in /home folder. We can also look for all the files with .log extension in /var/log folder, run

$ sudo find /var/log -type f -name *.log

find-files-based-on-exetension-linux

4) Searching Files in Multiple Directories

Let’s assume we want to search .sh extension files in /home and /root folder, run

$ sudo find /home /root -type f -name '*.sh'

find-files-from-multiple-directories-linux

5) Case-Insensitive File Search

For a case-insensitive search, use the -iname option, example is shown below,

$ sudo find /home -type f -iname CleanUP.SH
/home/linuxtechi/automation/cleanup.sh
$

The result of the command will find the file with name cleanup.sh, whether its in lower case or upper case or in mixed cases.

6)Exclude Specific Files or Directories

Let’s suppose we want to find all the files that are not the mentioned type, to achieve this we can use -not option in find command. Example is shown below,

$ sudo find /home -type f -not -name '*.mp3'

Use the -not option to exclude specific directories from the search results.

$ find /home -type f -not -path "./exclude/*"

7) Locate Files with Multiple Conditions

We can also combine more than one condition to search the files using regular expression , Let’s suppose we want to search files of ‘.sh’ and ‘.mp3’ extensions in our home directory, run

$ find $HOME -regex ".*\.\(sh\|mp3\)$"

Regular-Experssion-find-command

8) Combining Multiple Conditions

Combine multiple conditions with logical operators like -a (AND) and -o (OR) to fine-tune your search.

$ find $HOME -name "*.sh" -o -name "jumpscripts"
/home/linuxtechi/automation/cleanup.sh
/home/linuxtechi/dumpdata.sh
$

9) Search for Files with Specific Permissions

To search for files based on the permissions, use -perm option in find command. Find all files in /home folder with permissions ‘0777’, run

$ sudo find /home -type f -perm 0777

Search all the executable scripts in user’s home directory

$ find $HOME -type f -perm /a+x

10) Locate All Hidden Files

To search for all the hidden files in user’s home directory, run the command

$ find $HOME -type f -name ".*"

11) Search all the files with SGID

To locate all the files with SGID bits, we can use

$ sudo find / -perm /g=s
or
$ sudo find / -perm -2000

12) Find all the files with SUID

To locate all the files with SUID bits, run

$ sudo find / -perm /u=s
or
$ sudo find / -perm -4000

13) Search all files which are readable but don’t have execute permissions

Search for the files that are readable by everybody but can not be executed by anybody, run

$ sudo find $HOME -perm -a+r \! -perm /a+x

14) Search Files Basis on File Types

In single find command, we can search multiple file types,

$ find $HOME -type f,d,l

15) Locate Files by Ownership

To locate all the file that are owned by a particular user in /home directory use -user option, run following command,

$ sudo find $HOME -user linuxtechi

16) Locate Files by Group Ownership

To locate all the files that are owned by a particular group use -group option, below command will search all files which are owned by apache group.

$ sudo find / -group apache

17) Search for Files by Size

Use -size option in find command to search files based on the size. Run following command to find all files whose size is exactly 50MB.

$ find $HOME -size 50M
/home/linuxtechi/dbstuff
$

Search files whose is size greater than 50MB,

$ find $HOME -size +50M

Search files whose size is less than 50MB

$ find $HOME -size -50M

Locate all files whose size is in range between 40MB to 500MB

$ find $HOME -size +40M -size -500M

18) Restrict Find Command

To restricty the find command from descending into directories on other file systems, you can use the -xdev option. This option instructs find to stay on the same file system and not cross mount points. This is useful when you want to search for files within a specific file system and avoid traversing into separate partitions or devices.

Beneath command will search all files whose size is more than 100MB in / file system and exclude other mounted file system moreover it will redirect error message to /dev/null

$ find / -xdev -size +100M 2>/dev/null

xdev-option-find-command

19) Search by File Modification Time

For example, we want to search all the files that have been modified 10 days ago. We can accomplish that using ‘-mtime’ option in find command

$ sudo find / -mtime 10 2>/dev/null

20) Searching by File Access Time

Similarly like above example, we can also locate files that have been accessed 30 days ago using ‘-atime’,

$ sudo find / -atime 30 2>/dev/null

21) Search Empty Files and Directories

To search all the empty files in user’s home directory, run

$ find $HOME -type f -empty
or 
$ find $HOME -type f -size 0

Similarly, to locate all the empty directories

$ find $HOME -type d -empty

22) Search and Delete Files

Using find command, we search and delete the files using a single command. ‘-delete’ option in find command can delete files.

In following example, we are searching and deleting mp3 files from user’s home directory

$ find $HOME -type f -name "*.mp3" -delete

Search-and-delete-files-find-command-linux

Note : Above is destructive command, be careful while executing it.

23) Locate Largest and Smallest Files

To search largest and smallest file on the basis of their size, we will combine sort command along with find command & if we further want to list top three of those largest files, we will combine head command.

To list top three files in the user’s home directory, run

$ find $HOME -type f -exec ls -s {} \; | sort -n -r | head -3
51200 /home/linuxtechi/dbstuff
8276 /home/linuxtechi/.cache/gnome-software/appstream/components.xmlb
2764 /home/linuxtechi/.local/share/gnome-photos/tracker3/private/meta.db-wal
$

We can similarly find the smallest files in the user’s home directory,

$ find $HOME -type f -exec ls -s {} \; | sort -n | head -3

24) Search All log Files and Redirect them to a File

The -exec option in the find command is used to perform actions on the files or directories that are found during the search. It allows you to execute external commands, scripts, or other utilities on the files that match the specified criteria

$ find <path> <search-pattern> -exec <command> {} \;

Following command will locate all log files and redirect their names to a file /tmp/logsfiles.txt

$ sudo find /var -type f -name '*.log' -exec ls -lah {} \; > /tmp/logfiles.txt

find-log-files-redirect-them-linux

Another Example

$ sudo find / -type f -name "*.jpg" -exec cp {} /var/tmp/images \;

25) Search Files and Change their Permissions

Let’s suppose we want to search all files whose permissions is 777 and change their permissions to 644

$ find $HOME -type f -perm 777 -exec chmod 644 {} \;

26) Search Text from Files

Let’s assume we want to search error word in all log files, run following command

$ sudo find /var -type f -name '*.log' -exec grep -i 'error' {} \;
or 
$ sudo  find / -type f -name "*.log" -print0 | xargs -0 grep "error"

In above command we have combined find and grep command to accomplish the task.

Conclusion

The “find” command is undoubtedly a powerful tool for searching and managing files in Linux. Its flexibility and extensive range of options make it a must-have utility for any Linux user or system administrator. From basic file searches to complex operations, these 26 examples demonstrate the versatility and efficiency of the “find” command. Experiment with these commands and unleash the full potential of your Linux command line experience.

Read Also: 16 Useful ‘cp’ Command Examples for Linux Beginners

The post 26 Useful find Command Examples in Linux first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/find-command-examples-in-linux/feed/ 4
Tar Command in Linux with Practical Examples https://www.linuxtechi.com/tar-command-in-linux-with-examples/ https://www.linuxtechi.com/tar-command-in-linux-with-examples/#comments Fri, 07 Oct 2022 01:07:14 +0000 http://www.linuxtechi.com/?p=4511 In this post, we will learn tar command in linux with practical examples. Tar command is used for creating archive of multiple files and directories into single archive file, extension of archive file will always be ‘.tar’. Tar can further compress the archived file using ... Read more

The post Tar Command in Linux with Practical Examples first appeared on LinuxTechi.]]>
In this post, we will learn tar command in linux with practical examples.

Tar command is used for creating archive of multiple files and directories into single archive file, extension of archive file will always be ‘.tar’. Tar can further compress the archived file using gzip and bzip2 techniques. Tar stands for ‘Tape archive’ and used to create and extract archive files from the command line. Tar can also be treated as command line backup and restore utility.

Syntax

# tar <options> <files>

Options:

  • -c : create a new archive
  • -f : Archive file name
  • -t, –list : list the contents of an archive
  • -x, –extract, –get :  extract files from an archive
  • -d, –diff, –compare :  find differences between archive and file system
  • –delete : Delete from the archive.
  • -r, –append : append files to the end of an archive
  • -v : Verbose output
  • -u, –update : only append files newer than copy in archive
  • -X, –exclude-from=file : exclude patterns listed in file
  • -C, –directory=DIR: Change to DIR before performing any operations.
  • -j, –bzip2 : Compress and extract archive through bzip2
  • -J, –xz : Compress and extrach the archive through xz
  • -z, –gzip : Compress and extract the archive through gzip

Note: hyphen ( – ) in the tar command while using options is optional.

Without any further delay, let’s jump into tar command examples.

1) Creating an archive file

Let’s create a tar file of /etc directory and ‘/root/anaconda-ks.cfg’ file, run

# tar -cvf archive.tar /etc /var/log/syslog

Above command will create a tar file with the name “archive.tar” in the current folder. Tar file contains all the files and directories of /etc folder and /var/log/syslog file.

In above command, ‘-c’ option specify to create a tar file, -v’ is used for verbose output and ‘-f’ option is used to specify the archive name.

# ls -l archive.tar
-rw-r--r-- 1 root root 12554240 Oct 7 08:25 archive.tar
#

2) List content of archive file

Use ‘-t‘ option in tar command to view the content of tar files without extracting it.

# tar -tvf archive.tar

Listing a specific file or directory from tar file. In the below example, we are trying to list whether ‘syslog’ file is there in the tar file or not.

# tar -tvf archive.tar var/log/syslog
-rw-r----- syslog/adm 951215 2022-10-07 08:18 var/log/syslog
#

3)  Append files to the archive

‘-r’ option in the tar command is used to append or add file to existing archive file. Let’s add /var/log/auth.log file to archive.tar, run

# tar -rvf archive.tar /var/log/auth.log

Verify whether file is appended or not, run

# tar -tvf archive.tar var/log/auth.log
-rw-r----- syslog/adm 52790 2022-10-07 08:30 var/log/auth.log
#

Note: In the Compressed tar file we can’t append file or directory.

4) Extract archive file

To extract an archive file, use ‘-x’ option in the tar command as shown below.

# tar -xvf archive.tar

Above command will extract all the files and directories of archive.tar file in the current working directory.

5) Extract tar archive to specific folder

In case you want to extract tar file to a specific folder or directory then use ‘-C’ option followed by path of a folder. Example is shown below

# tar -xvf archive.tar -C /tmp/

6) Extract specific file from tar archive

Let’s suppose we want to extract “/etc/netplan/01-network-manager-all.yaml” file from the archive under /tmp folder.

Syntax : # tar -xvf {tar-file } {file-to-be-extracted } -C {path-where-to-extract}

# tar -xvf archive.tar etc/netplan/01-network-manager-all.yaml
etc/netplan/01-network-manager-all.yaml
#
# ls -l etc/netplan/01-network-manager-all.yaml
-rw-r--r-- 1 root root 104 Aug 9 12:55 etc/netplan/01-network-manager-all.yaml
#

7) Create and compress archive file (gzip)

We can compress archive file while creating it, let’s assume that we want to create a tar file of /etc and /opt folder and also want to compress it using gzip tool. This can be achieved using ‘-z’ option in tar command. Extensions of such tar files will be either tar.gz or .tgz

# tar -zcpvf archive.tar.gz /etc/ /opt/
Or
# tar -zcpvf archive.tgz /etc/ /opt/

8) Create and compress archive file (bzip2)

Let’s assume that we want to create compressed (bzip2) tar file of /etc and /opt folder. This can be achieved by using the option (-j) in the tar command. Extensions of such tar files will be either tar.bz2 or .tbz

# tar -jcpvf archive.tar.bz2 /etc/ /opt/
Or
# tar -jcpvf archive.tbz2 /etc/ /opt/

9) Exclude specific file type while creating archive

Using “–exclude” option in tar command we can exclude the specific file type while creating archive file. Let’s assume we want to exclude the file type of html while creating the compressed tar file, run

# tar -zcpvf archive.tgz /var/ /opt/ --exclude=*.html

10) List the content of compressed archive (tar.gz or .tgz)

Contents of compressed archive with extension tar.gz or .tgz is listed by using the option ‘-t’. Example is shown below :

# tar -tvf archive.tgz | more

output,

List-Content-Compressed-Archive-file

11) List the content of compressed archive (tar.bz2 or .tbz2)

Content of tar file with the extensions .bz2 or .tbz2 is viewed by using the option ‘-t’. Example is shown below :

# tar -tvf archive.tbz2 | more
or 
# tar -tvf archive.tar.bz2 | more

12) Extract compressed archive file (tar.gz or .tgz)

tar files with extension tar.gz or .tgz is extracted with option ‘-x’ and ‘-z’ as shown below,

# tar -zxpvf archive.tgz -C /tmp/

Above command will extract tar file under /tmp directory.

Note : Now a days tar command will take care compression file types automatically while extracting, it means it is optional for us to specify compression type in tar command. Example is shown below :

# tar -xpvf archive.tgz -C /tmp/

13) Extract compressed archive (tar.bz2 or .tbz2)

Archive files with extension tar.bz2 or .tbz2 is extracted using the option ‘-j’ and ‘-x’. Example is shown below

# tar -jxpvf archive.tbz2 -C /tmp/
Or
# tar xpvf archive.tbz2 -C /tmp/

14) Scheduling backup with tar command

There are some real time scenarios where we have to create tar file of specific files and directories for backup purpose on daily basis. Let’s suppose we have to take backup of whole /opt folder on daily basis, this can be achieved by creating a cron job of tar command. Example is shown below :

# tar -zcvf optbackup-$(date +%Y-%m-%d).tgz /opt/

Create a cron job for above command.

15) Create and compressed archive file with -T and -X option

In day to day activities, system admins might require to exclude and include files while creating archive using tar command. This can be achived by using include ( -T) and exclude (-X) file in tar command.

In tar command input file is specified after ‘-T’ option and file which consists of exclude list is specified after ‘-X’ option.

Let’s assume we want to archive and compress the directories like /etc , /opt and /home and want to exclude the file ‘/etc/sysconfig/kdump‘ and ‘/etc/sysconfig/foreman‘, Create a text file ‘/root/tar-include’ and ‘/root/tar-exclude’ and put the following contents in respective file.

# cat /root/tar-include
/etc
/opt
/home
#
# cat /root/tar-exclude
/etc/sysconfig/kdump
/etc/sysconfig/foreman
#

Now run the below command,

# tar zcpvf mybackup-$(date +%Y-%m-%d).tgz -T /root/tar-include -X /root/tar-exclude

16) View the size of .tar, .tgz and .tbz2 file

Use the following tar commands to view the size compressed archive files.

# tar -czf - data.tar | wc -c
427
# tar -czf - archive.tgz | wc -c
1450527
#
# tar -czf - archive.tbz2 | wc -c
1206287
#

17) Split big tar file into smaller files

In Linux like operating system big file is divided or split into smaller files using split command. Big tar file can also be divided into the smaller parts using split command.

Let’s assume we want to split ‘bigarchive.tgz‘ file into smaller parts of each 6 MB.

Syntax :  split -b <Size-in-MB> <tar-file-name>.<extension> “prefix-name”

# split -b 6M bigarchive.tgz bigarchive-parts

Above command will split the bigarchive.tgz file into the smaller files each of size 6 MB in current working directory and split file names will starts from bigarchive-partsaa bigarchive-partsag. In case if you want to append numbers in place of alphabets then use ‘-d’ option in above split command.

# ls -l bigarchive-parts*
-rw-r--r-- 1 root root 6291456 Oct 7 10:43 bigarchive-partsaa
-rw-r--r-- 1 root root 6291456 Oct 7 10:43 bigarchive-partsab
-rw-r--r-- 1 root root 6291456 Oct 7 10:43 bigarchive-partsac
-rw-r--r-- 1 root root 6291456 Oct 7 10:43 bigarchive-partsad
-rw-r--r-- 1 root root 6291456 Oct 7 10:43 bigarchive-partsae
-rw-r--r-- 1 root root 6291456 Oct 7 10:43 bigarchive-partsaf
-rw-r--r-- 1 root root 6291456 Oct 7 10:43 bigarchive-partsag
#

Now we can move these files into another server over the network and then we can merge all the files into a single tar compressed file using below cat command.

# cat bigarchive-parts* > bigarchive.tgz
#

That’s all from post, I hope you have learned tar command with above practical examples. Please share your queries and feedback in below comments section.

Also Read : How to Compare Files in Linux with diff Command

The post Tar Command in Linux with Practical Examples first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/tar-command-in-linux-with-examples/feed/ 6
14 grep command examples in Linux https://www.linuxtechi.com/grep-command-examples-in-linux/ https://www.linuxtechi.com/grep-command-examples-in-linux/#comments Fri, 19 Aug 2022 07:54:43 +0000 http://www.linuxtechi.com/?p=3082 Are you looking for hands on guide on Linux grep command ? In this guide, we will cover 14 grep command examples in linux. Grep is a command line tool in Linux/Unix systems that is used to search text or string from a file. Grep ... Read more

The post 14 grep command examples in Linux first appeared on LinuxTechi.]]>
Are you looking for hands on guide on Linux grep command ? In this guide, we will cover 14 grep command examples in linux.

Grep is a command line tool in Linux/Unix systems that is used to search text or string from a file. Grep stands for global regular expression print. When we run a grep command with specified string, if its is matched, then it will display the line of the file containing that string without modifying the contents of the existing file.

Syntax of grep command

$ grep  <Options> <Search String>  <File-Name>

Options:

Grep-Command-Options

Without any further delay, let’s deep dive into grep command examples.

1) Searching a word or string in a file

When we run grep command followed by search string or pattern then it will print the matching line of a file. Example is shown below.

Search a word “nobody” word in the file /etc/passwd file,

$ grep nobody /etc/passwd
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
$

2) Searching pattern in the multiple files

A word or a pattern can be searched in multiple files using grep command. Run following to search ‘linuxtechi’ word in /etc/passwd, /etc/shadow and /etc/gshadow files.

$ sudo grep linuxtechi /etc/passwd /etc/shadow /etc/gshadow

Output,

Search-Word-Multiple-files-Grep-command

3) Print file names that matches the pattern

Let’s assume we want to list the files names which contains word ‘root’, to do so use ‘-l’ option in grep command followed by word (pattern) and files.

$ grep -l 'root' /etc/fstab /etc/passwd /etc/mtab
/etc/passwd
$

4) Display the line number with output lines

Use ‘-n’ option in grep command to display line and its number which matches the pattern or word. In below example, pattern is ‘nobody’

$ grep -n 'nobody' /etc/passwd
18:nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
$

5) Invert the pattern match

Using the option ‘-v’ in grep command, we can display the lines which don’t match the pattern

$ grep -v 'nobody' /etc/passwd

 

Invert-Match-Pattern-Grep-Command

6) Print all lines that starts with specific pattern

Bash shell treats caret symbol (^) as a special character which marks the beginning of line or a word. Let’s display the lines which starts with “backup” word in the file /etc/passwd, run

$ grep ^backup /etc/passwd
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
$

7) Print all the lines that ends with specific word

Bash shell treats dollar symbol ‘$’ as a special character which marks the ends of line or word. List all the lines of /etc/passwd that ends with “bash” word.

$ grep bash$ /etc/passwd
root:x:0:0:root:/root:/bin/bash
linuxtechi:x:1000:1000:linuxtechi,,,:/home/linuxtechi:/bin/bash
$

8) Searching pattern recursively

‘-r’ option in grep command is used to search pattern recursively in folder and sub-folders.  Let’s suppose, we want to search a pattern ‘nologin’ in /etc folder recursively.

$ sudo grep -r nobody /etc
/etc/shadow:nobody:*:19101:0:99999:7:::
/etc/shadow-:nobody:*:19101:0:99999:7:::
/etc/passwd:nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
/etc/ssh/sshd_config:#AuthorizedKeysCommandUser nobody
/etc/passwd-:nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
$

Above command will search ‘nobody’ pattern in the “/etc” directory recursively.

9) Print all the empty lines of a file

Grep command can also print all the empty or blank lines from a file use the special character combination ‘^$’ , example is shown below:

$ grep '^$' /etc/sysctl.conf

output,

Print-Empty-Lines-Grep-Command

To print the line numbers of empty lines, run

$ grep -n '^$' /etc/sysctl.conf

10) Ignore letter case while searching

‘-i’ option in the grep command ignore case distinctions in patterns and data. When we use ‘-i’ then it will not discriminate upper case or lower case letters while searching.

Let’s assume we want search ‘IP_Forward’ string in sysctl.conf file, run

$ grep IP_Forward /etc/sysctl.conf
$
$ grep -i IP_Forward /etc/sysctl.conf
#net.ipv4.ip_forward=1
$

Grep command can also used to match only whole words using ‘-w’ option, example is shown below,

$ sudo sysctl -a | grep -w 'vm.swappiness'
vm.swappiness = 60
$

Above command will search and look for the lines which have exactly “vm.swappiness” word.

11) Matching multiple patterns

With the help of ‘-e’ option in grep command, we can search multiple patterns in a single command. Example is listed belpw:

$ grep -e nobody -e mail /etc/passwd
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
$
or 
$ grep -E "nobody|mail" /etc/passwd
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
$

12) Takes pattern from a file

‘-f’ option in grep command enables to take patterns from file. Example is demonstrated below:

First create a search pattern file with name “grep_pattern” in your current working directory. In my case put following content in it.

$ cat grep_pattern
^linuxtechi
root
false$
$

Now try to search using grep_pattern file.

$ grep -f grep_pattern /etc/passwd

Takes-Pattern-from-file

13) Count the number of lines that matches the pattern

If you wish to count number of lines that matches the search pattern then use ‘-c’ option in grep command.

Let’s consider we want to count the numbers of lines which ends with false word in /etc/password file, run

$ grep -c false$ /etc/passwd
6
$

14) Print N lines before & after pattern matching

Grep command can also print n number of lines before and after matching the pattern using -B and -A options respectively.

a) Print four lines before pattern matching

$ grep -B 4 "games" /etc/passwd

 

Print-Lines-Before-Matching-Pattern-Grep-Command

b) Print four lines after pattern matching, use -A option in grep command

$ grep -A 4 "games" /etc/passwd

 

Print-Lines-After-Matching-Pattern-Grep-Command

c) Print Four lines around the matching pattern, use -C option

$ grep -C 4 "games" /etc/passwd

 

Print-Lines-Around-Matching-Pattern-Grep-Command

That’s all from this guide, I hope these examples will help you to understand how to use grep command in linux more efficiently. Please do post your queries and feedback in below comments section.

Also Read: 10 rm Command Examples for Linux Beginners

The post 14 grep command examples in Linux first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/grep-command-examples-in-linux/feed/ 4
How to Download RPM Without Installing on RHEL 8 / CentOS 8 https://www.linuxtechi.com/download-rpm-without-installing-rhel-centos/ https://www.linuxtechi.com/download-rpm-without-installing-rhel-centos/#comments Sun, 20 Mar 2022 08:11:14 +0000 http://www.linuxtechi.com/?p=4581 While working on RHEL and CentOS Servers there are some scenarios where we want to download specific or set of RPM packages from the command the line without installing it. Though we can use wget command to download packages but wget will not download package ... Read more

The post How to Download RPM Without Installing on RHEL 8 / CentOS 8 first appeared on LinuxTechi.]]>
While working on RHEL and CentOS Servers there are some scenarios where we want to download specific or set of RPM packages from the command the line without installing it. Though we can use wget command to download packages but wget will not download package along with its dependencies.

On RHEL 8 or CentOS 8, DNF (or yum) is a command line package management utility. Using DNF or yum we can install, update and remove rpm packages. Apart from this it can also be used to download packages along with dependencies without installing them.

In this guide, we will cover how to download rpm packages without installing on RHEL 8 or CentOS 8 system.

Download Specific RPM Package

dnf or yum command on RHEL 8 or CentOS 8 has download flag which allows to download rpm package.

Syntax:

$ sudo dnf download <package-name>

Let’s assume, we want to download ‘nfs-utils’ package. Run

$ sudo dnf download nfs-utils

Above command will download the nfs-utils package in the present working directory. It will not download dependencies. Verify the downloaded package, run

$ ls
nfs-utils-2.3.3-26.el8.x86_64.rpm
$

Download RPM along with dependencies

Using ‘–downloadonly’ flag in dnf or yum command, rpm package along with its dependencies can be downloaded. We can also instruct dnf command to download rpm in particular folder using ‘–downloaddir’ flag.

Syntax:

$ sudo dnf install <package-name> –downloadonly –downloaddir <directory-path>

Let’s assume, we want to download ansible rpm along with its dependencies in package directory.

$ mkdir packages
$ sudo dnf install ansible --downloadonly --downloaddir ~/packages/

Download-RPM-Package-DNF-Command-RHEL

Once the above command is executed successfully, verify whether ansible rpm package is downloaded or not. Execute ls command,

$ ls -l packages/

Verify-Downloaded-RPM-Packages-ls-Command

Now we can make a tar file of these packages and transfer to a remote system where we want to install ansible and don’t have internet and repository connectivity on that system.

Download Group Package

Let’s suppose we want to download all the packages which comes under the group “Development Tools”, run beneath command.

$ sudo dnf group install "Development Tools" --downloadonly --downloaddir ~/dev-tools/ -y

Download-Development-tools-rhel-centos

Verify whether packages have been downloaded or not, run ls command

$ ls -l ~/dev-tools/

Verify-Group-Downloaded-Packages-ls-command

Great, above output confirms that all development packages have been downloaded under ~/dev-tools folder.

Note: Whenever we download packages with dnf  or yum command command and if we don’t pass –downloadidr flag then packages will be downloaded to ‘/var/cache/dnf/baseos-xxxx/packages/’, ‘/var/cache/dnf/appstream-xxxx/packages’ and ‘/var/cache/dnf/epel-xxxx/packages/’.

That’s all from this guide, I have found it informative. Kindly post your queries and feedback in below comments section.

The post How to Download RPM Without Installing on RHEL 8 / CentOS 8 first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/download-rpm-without-installing-rhel-centos/feed/ 9
How to Change Hostname in RHEL 8 / CentOS 8 https://www.linuxtechi.com/change-hostname-rhel-centos/ https://www.linuxtechi.com/change-hostname-rhel-centos/#respond Fri, 18 Mar 2022 02:35:14 +0000 http://www.linuxtechi.com/?p=3804 Hostname is the name or label of a computer or a network device. Computer or network device has it own IP address but it is very difficult for the humans to remember it that’s why hostname is set on computer and network devices. Hostname is ... Read more

The post How to Change Hostname in RHEL 8 / CentOS 8 first appeared on LinuxTechi.]]>
Hostname is the name or label of a computer or a network device. Computer or network device has it own IP address but it is very difficult for the humans to remember it that’s why hostname is set on computer and network devices. Hostname is a human readable string which one can easily remember.

In this guide, we will learn how to change hostname on RHEL 8 and CentOS 8 system. Basically, there are three different methods through which we can change hostname.

  • hostnamectl
  • nmtui
  • nmcli

Types of Hostname that we can set on RHEL 8 / CentOS 8 systems.

  • Static Hostname : It is conventional hostname that we set on the servers and as the name suggest hostname will be static and persistent across the reboot.Static hostname is stored in the file /etc/hostname.
  •  Transient Hostname : It is the hostname which is obtained from DHCP and mDNS. Transient hostname might be temporary because it is only temporarily written to kernel hostname.
  •  Pretty Hostname : It is a hostname that can include all kind of special characters. Pretty hostname is stored in the file /etc/machine-info .

Note : Default hostname on RHEL and CentOS system is ‘localhost.localdomain’, when it not set at the time of installation.

How to View Hostname on RHEL / CentOS ?

We can use hostname and hostnamectl commands to view the current hostname of our RHEL or CentOS system. Open the terminal and run,

$ hostname
OR
$ hostnamectl status
OR
$ hostnamectl

Sample output of above commands would look like below,

hostname-rhel-centos

Change hostname with hostnamectl Command 

hostnamectl command is used to set, change and query hostname. Basic syntax is listed below :

$ hostnamectl set-hostname <new_hostname>

Let’s set the static hostname ‘cloud.linuxtechi.local’

$ sudo hostnamectl set-hostname "cloud.linuxtechi.local"
$ exec bash

Verify the new hostname using hostnamectl and hostname command :

View-Hostname-RHEL-CentOS

How to remove or clear hostname ?

If you want to remove or clear hostname on RHEL or CentOS  system, then use beneath hostnamectl command,

$ sudo hostnamectl set-hostname ""
$ exec bash
$ hostname
localhost
$

Remove-hostname-hostnamectl

How to Set Pretty Hostname RHEL / CentOS  ?

To set the pretty hostname, use the following command

$ sudo hostnamectl set-hostname "LinuxTechi's RHEL 8 Laptop" --pretty

Set-Pretty-Hostname-RHEL-CentOS

How to remove or clear pretty hostname ?

Use the following hostnamectl command to remove or clear  pretty hostname,

$ sudo hostnamectl set-hostname "" --pretty

How to set hostname on the remote system from local machine ?

Using hostnamectl command we can also set hostname on remote system from the local system. Example is shown below,

Syntax :

$ hostnamectl set-hostname -H <Remote-System-IP> @<new_hostname>

Above command will use ssh for connecting and authentication for remote server.

$ sudo hostnamectl set-hostname -H 192.168.1.13 @cloud.linuxtechi.local
root@192.168.1.13's password:
$

Change hostname with nmtui command 

nmtui stands for ‘Network Manager Text User Interface‘, it is a text user interface which is used to configure networking along with hostname on modern Linux distributions.

When we type nmtui command below window will appear

$ sudo nmtui

nmtui-command-rhel-centos

Choose “Set system hostname” and then click on OK..

Set-Hostname-nmtui-RHEL-CentOS

Type the hostname whatever you want to set and then click on OK.

Choose-Ok-Set-Hostname-nmtui-command

To make the above changes into the effect, restart hostnamed service, run

$ sudo systemctl restart systemd-hostnamed

Now , we can verify new hostname using ‘hostname’ & ‘hostnamectl’ commands.

Change hostname with nmcli command

nmcli is a command line utility for configuring network connections and hostname on RHEL and CentOS systems.

To view the current hostname via nmcli command, run

$ nmcli general hostname
cloud.linuxtechi.local
$

To change the hostname, run

Syntax :

$ sudo nmcli general hostname <new_hostname>

$ sudo nmcli general hostname web.linuxtechi.local

Restart hostnamed service using beneath systemctl command

$ sudo systemctl restart systemd-hostnamed
$ hostname
web.linuxtechi.local
$

That’s all from this guide, I hope you found it informative. Kindly post you queries and feedback in below comments section.

Also Read : How to Create Sudo User on RHEL | Rocky Linux | AlmaLinux

The post How to Change Hostname in RHEL 8 / CentOS 8 first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/change-hostname-rhel-centos/feed/ 0
20 Useful Docker Command Examples in Linux https://www.linuxtechi.com/20-useful-docker-command-examples-linux/ https://www.linuxtechi.com/20-useful-docker-command-examples-linux/#comments Sat, 05 Feb 2022 08:18:06 +0000 https://www.linuxtechi.com/?p=5847 Docker container is one of the most emerging technologies now a days. Docker containers are generally used in CI/CD (Continuous Integration/Continuous Deployment) platform. Containers are the light weight VMs (Virtual Machines) which make use of underlying hypervisors resources like (RAM,CPU,HDD and Kernel). Docker command is ... Read more

The post 20 Useful Docker Command Examples in Linux first appeared on LinuxTechi.]]>
Docker container is one of the most emerging technologies now a days. Docker containers are generally used in CI/CD (Continuous Integration/Continuous Deployment) platform. Containers are the light weight VMs (Virtual Machines) which make use of underlying hypervisors resources like (RAM,CPU,HDD and Kernel).

Docker command is used to manage containers and images from command line. In this article we will cover 20 useful docker command examples in Linux. I am assuming docker is already installed on your Linux system and your regular user is added to docker group.

1) Verify Docker Version

First important task while working on docker containers is to know your docker version, run below docker command to know version

$ docker --version
Docker version 20.10.12, build e91ed57
$

2) View system wide Information

‘docker info’ command is used to view the system wide information like Docker root directory, OS version, Kernel Version, Docker Version, RAM, CPU and Docker Registry.

$ docker info

Docker-info-command-Linux

Docker-Info-Registry-Kernel

3) Search Docker Images

Using  ‘docker search’ command we can search the docker container images from docker hub registry, Let’s assume I want to search latest nginx docker images.

$ docker search nginx

Output of above command would look like below,

Docker-Search-Command-Output

4) Download Docker Container Images

Docker pull command is used to download container images from docker hub registry.

Syntax :

$ docker pull <Image-Name>

Docker pull command always  try to download latest version of image, though we can specify the particular version of  image. Let’s assume I want to download latest version of rsyslog image

$ docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
5eb5b503b376: Pull complete
1ae07ab881bd: Pull complete
78091884b7be: Pull complete
091c283c6a66: Pull complete
55de5851019b: Pull complete
b559bad762be: Pull complete
Digest: sha256:2834dc507516af02784808c5f48b7cbe38b8ed5d0f4837f16e78d00deb7e7767
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
$

Downloading specific image based on version, let’s assume, we want to download Ubuntu:20:04 docker image, run

$ docker pull ubuntu:20.04
20.04: Pulling from library/ubuntu
08c01a0ec47e: Pull complete
Digest: sha256:669e010b58baf5beb2836b253c1fd5768333f0d1dbcb834f7c07a4dc93f474be
Status: Downloaded newer image for ubuntu:20.04
docker.io/library/ubuntu:20.04
$

5) View Downloaded Docker Container Images

As we know that docker’s root directory is ‘/var/lib/docker’, so whenever we download images using docker pull command then all images will be saved in docker’s root directory.

To view all downloaded docker container images, run

$ docker image ls
or 
$ docker images

Output

Docker-Images-Command-Output

6) Run Docker Container

Containers are launched with ‘docker run’ command, let assume I want to run a container from nginx image.

$ docker run -it -p 9000:80 --name=myapp nginx

output

Docker-Run-Command-Example

Above will run a container with the name “myapp” and we also set pat rule in such a way that if any request comes to 9000 port on docker host then that request will be redirected to myapp container on 80 port. If you might have noticed that we directly get the console just after executing the command. Type exit to stop / shutdown the container and if want to get out from the container without stopping it then type “ctrl+p+q

Now you can access you nginx app on port 9000 using curl command,

$ curl http://<Docker-Host-IP-Address>:9000/

7) Run Container in detach mode

We can run a container in detach mode using -d option in ‘docker run’ command.Here detach mode means we will get command prompt after executing the docker run command. Example is shown below,

$ docker run -it -d -p 9080:80 --name=myapp2 httpd
f7dc2ece64708a9de5e53f341b0c7d17ac9189fb7c99079ad8744348bc5a6faa
$

8) View All Running Containers

Run ‘docker ps’ command is used to view all running containers

$ docker ps

docker-ps-command-output

To view all running along with exited or stopped containers, run

$ docker ps -a

9)  Container Console Access

To get container console access run beneath ‘docker exec’ command

sysops@linuxtechi:~$ docker exec -it myapp /bin/bash
root@3d5a0eef3e7a:/#

To come out of console type exit command

10) Start, Stop, Restart and Kill Containers

Just like virtual machines we can start, stop and restart docker containers.

Use below command to stop a running container

$ docker stop myapp2
myapp2
$

In place of container name we can also use container id

Use below command to start a container.

$ docker start myapp2
myapp2
$

Use below command to restart a container.

$ docker restart myapp2
myapp2
$

Just like process we can also kill a container, Use below command to kill a container.

sysops@linuxtechi:~$ docker kill myapp2
myapp2
sysops@linuxtechi:~$

11) Remove a Container

Docker Container is removed or deleted using ‘docker rm‘ command. ‘docker rm’ will work only when docker is stopped / shutdown.

Syntax:

$ docker rm {container_name_OR_container_id}

$ docker stop test-app
test-app
$ docker rm test-app
test-app
$

To remove a running container forcefully then use ‘-f’ option in docker rm command. Example is shown is below

$ docker rm -f nginx-app

Remove-container-forcefully

12) Remove Docker Container Images

Just like containers we can also delete or remove docker images. ‘docker rmi’ command is used to remove docker container images.

Let’s assume, we want to delete a docker image ‘Ubuntu:20.04’, run

$ docker rmi ubuntu:20.04
Untagged: ubuntu:20.04
Untagged: ubuntu@sha256:669e010b58baf5beb2836b253c14f7c07a4dc93f474be
Deleted: sha256:54c9d81cbb440897908abdcaa98674db831e40a66f704f
Deleted: sha256:36ffdceb4c77bf34325fb695e64ea447f629593310578d2
$

In above command we can use image id in place of image name

$ docker rmi 54c9d81cbb44

13)  Save and Load Docker Container Image

To save a docker image to a tar file, use ‘docker save‘ command, example is shown below:

$ docker save nginx -o mynginx.tar
$ ls -l mynginx.tar
-rw------- 1 sysops sysops 145931776 Feb 5 10:30 mynginx.tar
$

To load a docker image from a tar file, use ‘docker load‘ command

$ docker load -i mynginx.tar
Loaded image: nginx:latest
$

Note: These commands become useful when we want to transfer docker image from one Docker Host to another.

14) Copy files/folder to Container

We can copy files or folder to a container from the docker host using ‘docker cp’ command. In the following we are copying ‘mycode’ folder to myapp container

$ docker cp mycode myapp:/tmp

Copy-files-folder-Docker-Container

15) View History of a Docker Image

History of Docker image here means what commands are being executed while building docker images, we can view these commands using ‘docker history’

Syntax : #

$ docker history {Image_Name_OR_Image_id}

$ docker history nginx

Docker-History-Command-Output

16) View Logs from the Container

We can view the logs from the containers without login into it, Run ‘docker logs’ command

Syntax :

$ docker logs {container_name_or_container_id}

$ docker logs myapp

To view the live logs use ‘-f’ option in docker logs command

$ docker logs -f myapp

To view last 10 logs from a container, run

$ docker logs --tail 10 myapp

View-logs-from-docker-conatiner

17) Display Container(s) Resource Usage Statistics

To display CPU, memory, and network I/O usage of all the containers, run ‘docker stats’ command

$ docker stats

Docker-Stats-Command-Output

Above command will show live streaming of resource usage statistics of all the Containers.

To view stats of a specific container the run docker stats followed by container

$ docker stats myapp

Resource usage statistics without live streaming

$ docker stats --no-stream

We can display the running processes of a container with ‘docker top‘ command.

Syntax: #

docker top {Container_Name_OR_ID}

$ docker top myapp

docker-top-command-output

18) View Container IP Address

Container low-level information is displayed using ‘docker inspect’ command. We can fetch the ip address of a container from ‘docker inspect’ command

Syntax:

$ docker inspect -f ‘{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}’  <Container-Name>

Example

$ docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' myapp
172.17.0.2
$

19) Build Docker Container Image

Docker container image is build using ‘docker build‘ command but for docker build command to first we must create Dockerfile. Let’s suppose we Dockerfile is created under mycode folder then run following command to build docker image,

$ cd mycode
$ docker build -t mynginx:v2 .

Also Read : How to Build Docker Image with Dockerfile (Step by Step)

20) Set Tag to Docker Image

docker tag‘ command is used to set tag to a image.

Syntax :

$ docker tag source_image{:tag}  target_image{:tag}

Let’s suppose I want to set tag of source image ‘mariadb:latest’ as ‘mariadb:10.03’

$ docker tag mariadb:latest mariadb:10.03
$ docker images | grep -i mariadb
mariadb 10.03 45a5a43e143a 3 days ago 410MB
mariadb latest 45a5a43e143a 3 days ago 410MB
$

If you wish to upload image to your private registry then you tag the image in such a way that it should have registry url followed project and image.

$ docker tag mariadb:latest myregistry:5000/db/mariadb:10.03

Now login to your private registry using ‘docker login‘ command and run docker push command to upload it.

$ docker push myregistry:5000/db/mariadb:10.03

That’s all from this article. I hope you have found these examples informative. Please feel free to share your queries and comments in below comments sections.

Read Also: How to Create and Use MacVLAN Network in Docker

The post 20 Useful Docker Command Examples in Linux first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/20-useful-docker-command-examples-linux/feed/ 7
How to Configure IP Networking with nmcli Command in Linux https://www.linuxtechi.com/configure-ip-with-nmcli-command-linux/ https://www.linuxtechi.com/configure-ip-with-nmcli-command-linux/#respond Mon, 17 Jan 2022 06:07:34 +0000 https://www.linuxtechi.com/?p=13459 Nmcli (network manager command-line interface) is a command-line utility used to control the NetworkManager daemon which is used to configure network interfaces. With the nmcli utility, you can display, create, edit, enable and disable network interfaces or connections. It is especially handy for servers and ... Read more

The post How to Configure IP Networking with nmcli Command in Linux first appeared on LinuxTechi.]]>
Nmcli (network manager command-line interface) is a command-line utility used to control the NetworkManager daemon which is used to configure network interfaces.

With the nmcli utility, you can display, create, edit, enable and disable network interfaces or connections. It is especially handy for servers and headless systems which do not have a GUI.

In this tutorial, we focus on how you can configure IP networking with the nmcli command in Linux.

Basic Syntax

The nmcli command takes the syntax shown below:

$ sudo nmcli [OPTIONS] OBJECT {COMMAND | help }

Where Object can be any of the following:

  • Device or network interface managed by NetworkManager
  • NetworkManager’s connection.
  • NetworkManager’s stats

Let us now check out how you can configure IP networking with the nmcli command in Linux

Display active and inactive network interfaces

Without any command arguments, the nmcli command displays detailed information about all the network interfaces – both active and inactive.

$ nmcli

Some of the information displayed includes the state of the network connection, hardware type of the network adapter associated with the interface, MAC address, IPv4 and IPv6 addresses and default routes.

nmcli-command-output

To get a brief summary of the network interfaces run the command:

$ nmcli device status 
OR
$ nmcli dev status

nmcli-device-status

To list all the active interfaces on your system, execute the command:

$ nmcli connection show
OR
$ nmcli con show

The output displays the name of the connection, UUID, the type of connection (Wired or WiFi) and the device (network interface)

nmcli-connection-show

Alternatively, you can run the command:

$ nmcli connection show --active

Active-connection-nmcli-command

Specify output fields in the output

You can specify what fields you want to be displayed on the terminal. Valid fields include DEVICE, TYPE, CONNECTION, CONN-UUID, STATE, IP4-CONNECTIVITY, and IP6-CONNECTIVITY.

In the example below, we have chosen to display the DEVICE and DEVICE TYPE only.

$ nmcli -f DEVICE, TYPE device

nmcli-output-fields

Using the -p (pretty) option, you can display the output in a more human-readable format where the values and headers are well aligned.

$ nmcli -p device

nmcli-pretty-output

Configuring a static IP using the nmcli utility

In this section, we will demonstrate how you can configure a static IP address with the following values:

  • IP address:                   192.168.2.150/24
  • Default gateway:         192.168.2.1
  • Preferred DNS:           8.8.8.8, 8.8.4.4
  • IP addressing              static

Before we assign a static IP, let us check the current IP address of our system which is 192.168.2.104 as indicated.

ip-addr-command-output-linux

To set the static IP address with the connection name or profile called static-ip, IPv4 address 192.168.2.150, and default gateway  192.168.2.150 we will run the command:

$ sudo nmcli con add type ethernet con-name "static-ip" ifname enp0s3 ipv4.addresses 192.168.2.150/24 gw4 192.168.2.1

Note: In case you want to disable dhcp ip and configure static ip then run below,

$ sudo nmcli con add type ethernet con-name "static-ip" ifname enp0s3 ipv4.method manual ipv4.addresses 192.168.2.150/24 gw4 192.168.2.1

Next, we will configure the DNS server as follows.

$ sudo nmcli con mod static-ip ipv4.dns "8.8.8.8 8.8.4.4"

To activate the connection we will run the command:

$ sudo nmcli con up static-ip ifname enp0s3

Configure-IP-Network-nmcli-command-linux

We have simply added another IP address to our network interface enp0s3. To confirm that the IP address was successfully added, we will run the ip command:

$ ip addr

IP-address-confirmation-linux

Enabling / Disabling a network connection

In this section, we will explore how you can manage the connection by either activating or deactivating them. To disable or deactivate a connection, run the command:

$ sudo nmcli con down id "static-ip" ifname enp0s3

You can also simply leave out the ifname enp0s3 parameters.

$ sudo nmcli con down id "static-ip"

Disable-Connection-Nmcli-Command

To bring up or enable a connection, run the command:

$ sudo nmcli con up id "static-ip" ifname enp0s3

Alternatively, you can truncate the command as follows:

$ sudo nmcli con up id "static-ip"

Activate -connection-nmcli-command

To check out more on nmcli command options, simply run the command:

$ nmcli --help

nmcli-command-help

Conclusion

The nmcli utility is a useful tool for adding and managing network connections on Linux systems. It provides easy command-line options to help you configure networking particularly on headless servers. In this guide, we have demonstrated how you can add and manage network connections with the nmcli command in Linux.

Also Read: 9 tee Command Examples in Linux

The post How to Configure IP Networking with nmcli Command in Linux first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/configure-ip-with-nmcli-command-linux/feed/ 0
10 iftop Command Examples in Linux https://www.linuxtechi.com/iftop-command-examples-in-linux/ https://www.linuxtechi.com/iftop-command-examples-in-linux/#comments Mon, 23 Aug 2021 04:22:50 +0000 https://www.linuxtechi.com/?p=13004 System monitoring is a critical role that any sysadmin should undertake to ensure that systems and applications are running as expected. We have covered a few monitoring tools in the past including glances real-time monitoring tool and top command which provides detailed information about running ... Read more

The post 10 iftop Command Examples in Linux first appeared on LinuxTechi.]]>
System monitoring is a critical role that any sysadmin should undertake to ensure that systems and applications are running as expected. We have covered a few monitoring tools in the past including glances real-time monitoring tool and top command which provides detailed information about running process and other metrics such as uptime, CPU and memory usage.

Iftop is yet another monitoring tool that monitors network bandwidth in real-time. It captures total inbound and outbound data packets flowing through a network interface and displays the total bandwidth usage. In this guide, we walk you through the installation and the usage of the iftop command-line tool.

How to install iftop on Linux

Before we go any further, we need to install the bandwidth monitoring tool. And here’s how you can do it on various Linux distributions.

Install iftop on Ubuntu / Debian distributions

For Ubuntu and Debian-based distributions, run the command:

$ sudo apt-get install -y iftop

Install iftop on CentOS/RHEL/Rocky Linux

For RHEL-based distributions such as Rocky Linux, CentOS and Red Hat, you, first of all, need to enable the EPEL repository.

$ sudo yum install -y epel-release

Then execute the command:

$ sudo yum install iftop
Or
$ sudo dnf install -y iftop

Install iftop on Fedora 

For Fedora, run the command:

$ sudo dnf install -y iftop

Install iftop on Arch Linux / Manjaro 

For Arch-based distributions such as Manjaro, Endeavor OS, and Arch Linux to mention a few, run the following pacman command:

$ sudo pacman -S iftop

Let’s now have an overview of some of the common iftop command usages.

1)  Display overall bandwidth usage metrics

Without any arguments, the iftop command displays bandwidth usage of all the network interfaces attached to your system. simply invoke the command:

$ sudo iftop

View-bandwidth-all-interface-iftop-command

2) Display bandwidth statistics of a specific network interface 

To narrow down and display the statistics of a specific network interface, use the -i flag followed by the interface name. For example, If you want to display the bandwidth activity associated with an interface, say, enp0s8 , run the command:

$ sudo iftop -i enp0s8

Bandwidth-Usage-Specific-NIC-iftop-Command

3) Disable or hide the top bar graph

To hide or disable the bandwidth scale or bar located at the top of the terminal, use the -b option.

$ sudo iftop -b

Hide-Bandwidth-Scale-iftop-Command

4) Disable hostname lookup

To disable hostname lookup, use the -n option. For instance, the example below ignores the hostname lookup of the sites being accessed using the enp0s8 network interface

$ sudo iftop -n -i enp0s8

Disable-hostname-lookup-iftop-command

5) Display intuitive text output

To display the output in a more intuitive manner, instead of a tabular format as we have witnessed in previous examples, use the -t option shown.

$ sudo iftop -t

Display-intuitive-output-iftop-command

6) Display traffic flowing in and out of a subnet

If you are in a subnet, say, 192.168.2.0/24, and you want to analyze inbound and outbound network traffic, run the command:

$ sudo iftop -F 192.168.2.0/24

7)  Sort the displayed output by source address

If you wish to sort the traffic analysis data based on the source addresses run the command:

$ sudo iftop -o source

Sort-Display-output-iftop-Command

8) Sort displayed output by destination address

Conversely, to sort the traffic by destination address, run:

$ sudo iftop -o destination

Sort-Destination-Address-iftop-Command

9) Display bandwidth usage in bytes

To display the bandwidth usage of lan card, use -B option followed by interface, example is shown below

$ sudo iftop -B -i enp0s8

Sample output

Display-Bandwidth-Usage-in-Bytes-iftop-Command

10) Display man pages

For getting more help on iftop command then refer its man page.

$ man iftop

Man-Page-iftop-Command

That’s all from this, please do share your feedback and queries in below comments section.

The post 10 iftop Command Examples in Linux first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/iftop-command-examples-in-linux/feed/ 1
How to Use GNU Screen to Manage Terminal Sessions in Linux https://www.linuxtechi.com/screen-command-linux-terminal-sessions/ https://www.linuxtechi.com/screen-command-linux-terminal-sessions/#respond Tue, 22 Jun 2021 02:52:23 +0000 https://www.linuxtechi.com/?p=12664 GNU Screen is a terminal multiplexer which allows to have multiple terminal sessions inside the main terminal. So why we need GNU Screen? – Sometimes we may face some issues like automatically terminating the remote ssh connections due to network issues. It may be painful ... Read more

The post How to Use GNU Screen to Manage Terminal Sessions in Linux first appeared on LinuxTechi.]]>
GNU Screen is a terminal multiplexer which allows to have multiple terminal sessions inside the main terminal.

So why we need GNU Screen? – Sometimes we may face some issues like automatically terminating the remote ssh connections due to network issues. It may be painful if the task is running on production environment. So, to handle this kind of issues, separate screen session is recommended which does not terminate with the end of terminal sessions.

In the Linux and Unix systems, we have terminal multiplexer tool called screen which is used to manage terminal sessions. In this article we will cover how to use GNU screen in Linux to manage terminal sessions while working on important task in production systems.

GNU Screen Command Installation

Installation of the screen package in the Linux system is simple and easy. Some of the modern operating systems come with screen applications pre-installed. Run the following command to verify the availability of screen.

$ screen --version

Output:

Screen version 4.08.00 (GNU) 05-Feb-20

If you get other output, you do not have a screen tool available on your system. Run the following command to install the screen package.

Ubuntu/Debian

$ sudo apt-get install screen -y

RHEL/CentOS

$ sudo yum installs screen -y        // RHEL 7
$ sudo dnf install screen -y         // RHEL  8

Starting Screen in Linux

One the installation is completed, simply run the command screen to start screen sessions.

$ screen

Output:

Screen-Command-Output-Linux

Create Screen Session with name

Using screen command followed by option -S , you can create a named screen session . In this example, I have used screen-linuxtechi as the name of the screen session. You can choose your preferable name.

$ screen -S screen-linuxtechi

Listing screen parameters

Screen provides some useful parameters and commands. To list the available parameters, press ctrl-a followed by ? .

Note: screen uses the key ctrl+a as a prefix. For example, to list the screen parameters you need to press ctrl and a together ,release the key and press the key ? . In the same way you can use other parameters.

Output:

Screen-Command-Parameters

List Screen Sessions

Use the following command to list the available screen sessions.

$ screen -ls

Output

List-Screen-Sessions-Linux

Detach Linux Screen Session

One of the useful features provided by screen application is you can detach the screen session and reattach when needed. To detach the current screen session, press ctrl-a followed by d.

Detach-Screen-Session-Linux

Reattach Linux Screen session

The detached screen session can be attached again using screen command with option -r followed by screen session name. List out the detached screen session using command screen -ls , find the screen session name and attach. In this example I have attached the session 25148.pts-0.LinuxTechi

$ screen -ls
$ screen -r 25148.pts-0.LinuxTechi

Screen sessions can be reattached using only screen id or screen name. In the above example, 25148 is the ID and pts-0.LinuxTechi is the name of the screen 25148.pts-0.LinuxTechi.

$ screen -r 25148
$ screen -r pts-0.LinuxTechi

Split Linux Screen Windows

Sometimes you may need to split the screen windows into multiple screens to perform several tasks. Splitting can be done horizontally as well as vertically.

Vertical 

To split  Linux screen windows vertically click ctrl-a followed by | . By repeating the same process, you can split n numbers of screen windows.

Split-Linux-Screen-Vertically

Horizontal

Horizontal splitting of the screen windows can be done by clicking ctrl-a followed by S (Upper case). Repeat the same process to create n number of vertical windows.

Horizontal-Screen-Spliting-Linux

Create new terminal in splitted session

Whether you split the screen horizontally or vertically, it will not create any new terminal. To create the new terminal in the screen, you need to switch to new split screen windows using ctrl-a followed by Tab. Now press ctrl-a and c (lowercase) to create a terminal.

Splited-New-Terminal-Linux

Unsplit screen windows

To unsplit the splitted screen windows, you can simply apply ctrl-a with key Q

Lock screen sessions

To protect from unauthorized access, screen sessions can be locked without locking normal session users. To lock the screen terminal, use the command ctrl-a followed by key x (Lowercase) . You will be prompted to set up the password, apply your protection password and that’s all.

Lock-Screen-Session-Linux

Find owners of screen sessions

Screen stores opened screen sessions information at the directory /var/run/screen. List out the contents stored inside the directory to find the owner of the screen.

$ ls -ltr /var/run/screen

Output:

Owners-Screen-Session-Linux

Terminate the screen sessions

One the task is completed, you can destroy the screen sessions using the command ctrl-a followed by k . You will be prompted for user confirmation, type y to terminate the session.

Terminate-Screen-Session-Linux

Accessing the screen help page

Run the following command to access screen help page

$ screen --help

Run the following command to access the screen user manual page.

$ man screen

Some useful screen command’s parameters

  • Ctrl-a  +c  => Create a new screen window with terminal
  • Ctrl-a + ?  => List screen parameters
  • Ctrl-a + A => Rename the current screen window
  • Ctrl-a + tab => Switch to the next window
  • Ctrl-a + S => Split the window horizontally
  • Ctrl-a + | => Split the window vertically
  • Ctrl-a + d => Detach the screen
  • Ctrl | d => Terminate the screen

Conclusion

In this article we have learned different gnu screen commands to manage Linux terminal sessions. If you have any suggestions and feedback, please leave a comment below.

Recommended Read : Learn how to Record and Replay Linux Terminal Sessions Activity

The post How to Use GNU Screen to Manage Terminal Sessions in Linux first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/screen-command-linux-terminal-sessions/feed/ 0
8 Quick Date Command Examples in Linux https://www.linuxtechi.com/linux-date-command-with-examples/ https://www.linuxtechi.com/linux-date-command-with-examples/#respond Mon, 10 May 2021 03:08:14 +0000 https://www.linuxtechi.com/?p=12531 Maintaining accurate date on a Linux system is one of the essential skills that any Linux user should have at their fingertips. The Linux date command is used to display and set the date and time settings on a Linux system.  This tutorial gives you ... Read more

The post 8 Quick Date Command Examples in Linux first appeared on LinuxTechi.]]>
Maintaining accurate date on a Linux system is one of the essential skills that any Linux user should have at their fingertips. The Linux date command is used to display and set the date and time settings on a Linux system.  This tutorial gives you a glimpse of how you can use the date command to display and set the date on your Linux system.

Basic Syntax

The basic syntax of the date command is provided below

$ date [option]… [+format]

1 ) Date command without options

In its basic form, without any command options, the date command displays your current date and time including the day of the week, month, year, the time in hh:mm:ss format, and the timezone as presented below.

$ date
Sun May  9 15:41:17 IST 2021
$

2) Display the date and time in UTC

To display time in UTC (Coordinated Universal Time ),previously referred to as GMT (Greenwich Mean Time), append the -u option.

$ date -u
Sun May  9 10:11:59 UTC 2021
$

3 ) Display a specific date in a string format

You can display a specific date in a string format using the –date option as illustrated below. Take note that this does not affect your system’s date and time, rather it simply converts the date format to a string.

$ date --date="10/10/2021"
Sun Oct 10 00:00:00 IST 2021
$

4) Use the date command to check past dates

The date command can also print the date and time in the past relative to your current date.

For example, to check what the date was 9 days ago run the command.

$ date --date="9 days ago"
Fri Apr 30 15:45:28 IST 2021
$

To view the date two weeks earlier, run the command:

$ date --date="2 weeks ago"
Sun Apr 25 15:47:11 IST 2021
$

To check the date three months ago, execute:

$ date --date="3 months ago"
Tue Feb 9 15:47:52 IST 2021
$

To print the date 3 years ago, run:

$ date --date="3 years ago"
Wed May  9 15:49:04 IST 2018
$

5) Use the date command to check future dates

Just as you can check past dates, the date command also allows you to display future dates.

For example, to check tomorrow’s date run:

$ date --date="tomorrow"
Mon May 10 15:50:14 IST 2021
$

To check what the date will be exactly a week from now, run:

$ date --date="next week"
Sun May 16 15:51:03 IST 2021
$

To display what the date will be in two weeks’ time execute:

$ date --date="2 weeks"
Sun May 23 15:51:46 IST 2021
$

To display the date 4 months from now run:

$ date --date="4 months"
Thu Sep  9 15:52:33 IST 2021
$

And to check the date 2 years from now run:

$ date --date="2 years"
Tue May  9 15:53:20 IST 2023
$

6) Date formatting options

The date command comes with many options that allow you to customize the date output. Listed below are some of the formatting options available.

  • %D – Display date in the format mm/dd/yy
  • %Y – Year (e.g., 2021)
  • %m – Month (01-12)
  • %B – Month name in the full string format (e.g., February)
  • %b – Month name in the shortened string format (e.g., Feb)
  • %d – Day of month (e.g., 01)
  • %j – Day of year (001-366)
  • %u – Day of the week (1-7)
  • %A – Weekday in full string format(e.g., Friday)
  • %a – Weekday in shortened format (e.g., Fri)
  • %H – Hour (00-23)
  • %I – Hour (01-12)
  • %M – Minute (00-59)
  • %S – Second (00-60)

The syntax for using the date option is quite simple:

$ date “+%option”

For example, to print the date in yy/mm/dd format, run

$ date "+%Y-%m-%m"
2021-05-05
$

To print the day of the week, month, year, and current time run:

$ date "+%A %B %Y %T"
Sunday May 2021 15:55:56
$

7) How to set the date and time

The date command also allows you to set the date and time. For example, to set the date and time to 25, June 2021 at 11:15 am, run the command:

$ sudo date --set="20210625 11:15"
Fri Jun 25 11:15:00 IST 2021
$
NOTE:

Setting the system’s date and time this way is discouraged since the time is most likely to be inaccurate. A better way to achieve this is to use the chrony utility which is a replacement for the now deprecated ntpd daemon. In fact, modern systems such as CentOS 8 / RHEL 8 don’t support NTP. We have a  detailed guide on how to sync time and date using chrony.

In case you want to change time zone then use timedatectl command, example is shown below.

$ sudo timedatectl set-timezone Asia/Kolkata

8) Using Date command in variable

Sometime while creating a shell script, we save date command to a variable and then later we create log file using that variable, examples is shown below,

#!/bin/bash
LOGFILE=/tmp/logs-$(date +%d-%m-%Y_%T)
echo "##Check Cluster for Failed Resources##"  >> $LOGFILE
crm_mon -1 -rf | grep FAILED  >> $LOGFILE
echo -e "\n\n" >> $LOGFILE
echo "##Check Cluster for Stopped Resources##"  >> $LOGFILE
crm_mon -1 -rf | grep -i STOPPED  >> $LOGFILE
echo -e "\n\n" >> $LOGFILE

Summary

We hope we have shed light on the use of the Linux date command, and we trust you can use it to display the system’s date and customize the output to your preference.

Also Read : 9 tee Command Examples in Linux

The post 8 Quick Date Command Examples in Linux first appeared on LinuxTechi.]]>
https://www.linuxtechi.com/linux-date-command-with-examples/feed/ 0