Connect with us

Linux

mail Command in Linux/Unix with 10+ Examples [2019]

Last Updated on

Let’s Learn mail Command in Linux/Unix with Practical Examples :

The mail command in linux/unix is a powerful tool once system administrators get to know their way around it. You can use the shell to monitor processes, automate backups, and parse data.

Some command line utilities can be used for convenience when manipulating applications from the somewhat unfriendly screen. When the need to send an email via the command line option, there are numerous ways to go about it.

In this article, you will learn how to send and read emails using the popular commands and learn how to send mail using a shell script. It is also vital that you learn how to send Linux mail attachments. The root user should is the only authorized user who can install these mail packages.

The Common Mail Package Installations:

Command On Debian/Ubuntu On CentOS/RedHat
mailutils $ sudo apt-get install mailutils # yum install mailx
mutt $ sudo apt-get install mutt # yum install mutt
mpack $ sudo apt-get install mpack # yum install mpack
telnet $ sudo apt-get install xinetd telnetd # yum install telnet-server telnet
curl $ sudo apt-get install curl # yum install curl
sendmail $ sudo apt-get install sendmail # yum install sendmail
swaks $ sudo apt-get install swaks # yum install swaks

Some of the command line options taken by most mail commands are:

  • -s denotes the mail’s subject
  • -a for denoting attachment
  • -c for the copy email address (CC)
  • -b for the blind copy email address (BCC)

1. Using mail command in Linux

The Linux mail command in Linux/Unix is quite popular and is commonly used to send emails from the command line. Mail is installed as part of mailutils and mailx packages on Debian and Redhat systems respectively. The two commands process messages on the command line.
To install mail command in Debian and Ubuntu Systems, run

For RedHat & CentOS systems run

If the command is successfully installed, test the application by using the following format and press enter:

Replace you@youremailid.com with your email address.

After pressing ‘Enter’, you’ll be prompted for a Carbon Copy (Cc:) address.

If you wish not to include a copied address, proceed and hit ‘Enter’
Next, type the message or the body of the Email and hit ‘Enter’

Finally, Press Ctrl + D simultaneously to send the Email.

Alternatively, you can use the echo command to pipe the message you want to send to the mail command in Linux/Unix as shown below.

To send an email to many recipients run

Let’s assume you have the message that you want to send in a text file. How do you send it ?
To accomplish this, run the command below

You can create a text file as shown

Then add content to the file

Finally, send the message content

To send an attachment use the command below

The -a flag defines the file attachment.

2. Using the mailx Command in unix/linux

Mailx is the newer version of Linux mail command and was formerly referred to as nail in other implementations. Mailx has been around since 1986 and was incorporated into POSIX in the year 1992.

Mailx is part of the Debian’s mail compound package used for various scenarios. Users, system administrators, and developers can use this mail utility. The implementation of mailx also takes the same form as the mail command line syntax.

To install mailx in Debian / Ubuntu Systems run

To install mailx in RedHat & CentOS run

You may use the echo command to direct the output to the mail command without being prompted for CC and the message body as shown here:

3. Using the MUTT Command

Mutt is a lightweight Linux command line email client. Unlike the Linux mail command that can do basic stuff, mutt can send file attachments. Mutt also reads emails from POP/IMAP servers and connecting local users via the terminal.
To install mutt in Debian / Ubuntu Systems run

To install mutt in Redhat / CentOS Systems run

Here is how to use it. When using the mutt command, you can send an empty message with the < /dev/null right after the email address.

The mutt command supports the Linux mail attachment by using the –a option in this format.

The above example sends an attachment containing sql logs to the specified email address.
Mutt command recognizes file type and therefore will not send HTML file as plain text. For instance:

4. Using mpack Command

The mpack command is used to encode the file into MIME messages and sends them to one or several recipients, or it can even be used to post to different newsgroups.

To install mpack in Debian / Ubuntu Systems run

To install mpack in Redhat / CentOS Systems run

Using mpack to send email or attachment via command line is as simple as:

5. Using SSMTP Command

The sSMTP command allows the user to send emails from the SMTP server via the command line. For example, to send a test email to you@youremailid.com use the following syntax:

Hit CTRL+D to send the email.

6. Using the telnet Command

Telnet is a favourite of the system Administrators who use it to test remote port connectivity. It can also be used to login to the server remotely. Telnet is useful for Linux network troubleshooting email problems.

To install telnet in Debian/ Ubuntu Systems run

To install telnet in RedHat / CentOS Systems run

To listen to a port, you use the following format:

7. Using Sendmail

This command is another popular SMTP server used in many distributions.

To install sendmail in Debian/ Ubuntu Systems run

To install sendmail in RedHat / CentOS Systems run

You can use the following instructions to send email using the command:

The above command sends a file saved as email.txt in the temp folder.

8. Using the CURL Command

This utility is known for file transfers between servers and supports many protocols like the SMTP, POP3, HTTP, and the FTP. It mainly used because of its native PHP implementation meaning it supports the native server-side scripting language.

To install Curl in Debian/ Ubuntu Systems run

To install Curl in RedHat / CentOS Systems run

Sending an email with CURL will force you to set up the SMTP connection and turn on access for less secure apps.

The above command uses the –-url –-user flags to define SMTP connection settings. When using the –-ssl-reqd flag you must ensure that the connection is running on SSL or TLS. The command option requests the connection to be terminated if the server does not support a secure connection, i.e. SSL /TLS.

The –-mail-from flag specifies a single address that the issued email address should be used to send the mail, in this case it is you@youremailid.com. The –-mail-rcpt flag denotes the recipient address, in our case, the mail will be delivered to user@niceperson.com . You can use this flag multiple times for different addresses.

The command option --upload-file is used to transfer the specific file “mail.txt” to a remote URL. If no file name is issued you must use a trailing / after the last directory to indicate no file name was given.

9. Using the Swaks Command

The swaks command is flexible, scriptable and a simple SMTP test utility. Very useful in handling SMTP features like the TLS and authentications.

To install swaks in Debian/ Ubuntu Systems run

To install swaks in RedHat / CentOS Systems run

A simple implementation of the swaks command is to use the following flags:

  • Server –s
  • The user –au
  • The password –ap
  • The address of the recipient
  • The –tls is necessary if you are connecting to port 587

10. Sending Mail from a Shell Script

With all the email command line basics covered, you should be ready to send your first mail using a shell script. Here is an example of a shell script that can send an email. The output of the command sends the status of your PC to the chosen email.

Save the content above on your Linux server and run it to send the output of the df –h command to your email. A better way of sending emails using a shell script is to let the script write the data to a text file and send it to the specified email. For example:

If you can remember the mutt command, here is how you can use it to send attached systems backups. The script below will send the directory as archived and use the mutt command to send it as an attachment. In this case, “echo” is used to add a blank space to the body of the email.

11. How to Read Mails in Linux

Reading emails from the terminal may not be as enjoyable as sending emails. The mail command in linux/unix will give you version of the mail program installed. All Linux messages are installed in personal mailboxes, for example if your name was Linus, your incoming mails will be stored in the /var/spool/mail/ directory. On the other hand, mails sent to the root user are by default sent to the /var/spool/mail/root folder. Reading mails from this folder utilises the command cat in the following format:

The most commonly used syntax utilizes the mail command in this format:

A simple output from the above command gives:

At the end of the output is a question mark that prompts for your input in the form of a command. Key in the number that you want as listed on the screen above and press enter. When done reading, press on letter Q to load the previous screen. When you are entirely done press letter Z followed by the enter key to bring your back to the list of emails. The mail command reads all emails from the “var/mail/” directory. Always make sure that you are reading from the correct user directory if your server hosts multiple domains.
All these commands should get you started with sending emails from the Linux terminal and understand the basic knowledge of using executable shell scripts. More details on these email commands and their respective flags are found on the “man page.”

How to Troubleshoot Mail Problems

Diagnosing email problems covers a broad range of services. Some errors are easy to handle while others may require some sort of analysis. If everything seems to be working okay, the next step is to check the email service logs found in the /var/log/maillog file. To view the last part of an email log, use the tail command line utility (by default tail without any option will give the last ten lines). To set the number of lines to view, use the following format:

The above command displays the last 30 lines of the maillog content. Use the log file to identify any visible error.

Checking mails that are sent through the system can be traced to the /var/spool/postfix directory. Within this directory, there are subdirectories each denoting an active, deferred or bounce state. Here are some of the common commands used when probing email issues:

Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Linux

cat command in Unix/Linux with 10+ examples [2019]

Last Updated on

Let’s Learn cat command in Unix/Linux with Practical Examples :

The cat command in Unix/Linux is one of the most commonly used Linux commands on a day-to-day basis whether by novices or experienced Linux users. cat is short for concatenating and is mainly used for creating either single or several files at an instance, or viewing the contents of a file. In this article, we dive deeper and explore the cat command in Unix/Linux with example usages.

Cat command in Linux with examples

The most basic syntax for using cat command is as shown below

Let’s now take a closer look at the options that are mostly used with the cat command.

1. To view file content using cat command

To have a peek at a file without any options, simply use the syntax

For instance, to check the contents of a file /etc/hosts/code> run the command:

Sample output

cat command in Unix/Linux

2. View Mutiple files in a single command

To view multiple files at a go with cat command, use the syntax:

For example

Sample output

cat command in Linux

3. Display line numbers using the -n option

To make your display neater, and more presentable, you may want to number the lines of your output. To achieve this, use the -n option as shown below

For instance

Sample output

cat command in Unix/Linux

4. Create a file using the cat command

To create a file using cat command use the syntax

Next, type the contents of the file and finally hit CTRL +D to save the file

cat command in Linux create a new file

5. Copy contents of one file onto another

With cat command, you can easily copy file contents of one file into another using the standard redirection operator > as shown below.

If the file being copied to does not exist, it will be created automatically.

cat command in Linux

NOTE

Extra caution should be taken while using the standard redirection operator because it overwrites the contents of an existing file.

6. Redirect several files into one file

Similarly, you can redirect content from multiple files into one file using the syntax:

Sample output

7. Appending text to a file

if you want to append text and not overwrite the existing content, use the double greater sign symbol (>>). The content of one file will be added or appended at the end of the next text file.

8. Redirect standard input using redirection operator

you can use the redirection operator less than (<) to read contents from a file. The syntax for this is:

Sample output

9. Display the ‘$’ sign at the end of every line

If you wish to display the $ at the end of every line, use the -e option as shown below:

Sample output

From the output above, you can see that there a dollar sign ($) at the end of every file.

10. Display all files of a certain type

To display the content of all files of a certain file type, for example, text files use the wildcard symbol as seen in the command below

Sample output

As you can see from the output above, the command displays all content from all the text files with a .txt file extension.

Take away

In this article, we demonstrated the usage of cat command alongside some helpful examples and tips. The cat command is usually helpful in creating and viewing text files as well as appending content at the end of a file. We do hope that this tutorial was helpful. Fee free to try out some of the commands.

Continue Reading

Linux

Whereis command in Linux with 10+ Examples [2019]

Last Updated on

Let’s Learn whereis command in Linux with Simple Examples :

While working away on the command-line, one might need to find out the location of a command or binary file. The find command can be used for this task, but it is painfully slow and ends up taking much of your time and may also provide undesired results. The whereis command in Linux is ideal for quickly finding the location of a binary or source file in a system.

Whereis command in Linux is preferred due to its speed and accuracy in finding out the location of a command or binary files. More importantly, running the whereis command doesn’t require you to have root privileges. Let’s dive in and take a look at the whereis command usage with examples.

Whereis command usage in Linux

The basic syntax of the whereis command is:

1) Find the location of a command

To find out the location and man pages of a Linux command for instance,mkdir run the command

Sample output

whereis command in linux

2) Search for specific files/manuals

If you wish narrow down your search specifically to the binary file, use the -b option as shown in the command below.

Sample output

whereis command usage

To search for man pages only use the -m option as shown.

Sample output

3) View paths that whereis uses for searching

To take a quick peek at the directories that whereis command traverses while searching for command , files and man pages, use the -l option.

Sample output

whereis command in linux

4) Limit the search depth for whereis command

Usually, whereis command searches for commands and files in well-defined, hard-coded paths. However, you can limit the search depth using the -B option. For instance, to limit whereis to search binary files up to /bin, use the -B option as shown:

the -f option terminates the directory list whilst signaling the beginning of file names.

To limit the search directory for man pages, use the -M option as shown

Sample output

5) Check whereis version

if you wish to check the version of whereis command, use the -V option or –version flag as shown.

OR

Sample output

whereis command usage

6) Display whereis help options

To view the help page section that gives more insight on the options that can be used by whereis command, use the -h option or –help flag.

OR

Sample output

And with that, we come to the end of our tutorial. We welcome you to try out the commands and get back to us with your findings.

Continue Reading

Linux

Grep Command In Unix/Linux with 25+ Examples [2019]

Last Updated on

Let’s Learn Grep Command in Unix/Linux with Simple Examples :

New Linux users get anxious when confronted with the prospect of searching for a particular string in a file. Some have no idea what to or where to start. Here is an article to make your work a little easier. grep command in unix/linux is your rescue!

GREP  is a powerful tool Linux System Administrators use to search for specific file patterns. If by any chance your distribution does not have it installed you can use the following command to install it:

On Debian or Ubuntu

On RHEL, CentOS

On Fedora 22 and later

GREP derives its name from a Linux text editor ed, which uses the similar search operation written as g/re/p. Grep also stands for global regular expression print.

Grep command in unix/linux Syntax

The command line syntax used for grep take different forms but here are some of the few command line structures

grep [OPTIONS] PATTERN [FILE…]

The command searches for a particular pattern that matches the expression against a text file or a stream of input. However, it is important to note the three other variants of the GREP command in unix/linux :

• egrep, which also takes the form of grep –E
• fgrep, which takes the form of grep –F
• rgrep, which takes the form of grep –r

Much as the three variations are no longer supported, it allows for applications that use them to continue running without any modifications. The best way to learn about GREP is by using grep command with examples.

1. Search and Find Files

When you are looking for a file or a program that you need to ascertain version, GREP will come to your rescue. The primary usage of the command should give the output in a specified format.

The command displays string Linux if found in the file index.html

2. Searching strings with case insensitive option

If you want to display all string literals with the same name regardless of whether they are case sensitive or not, you add the –i flag as follows

The result will give an output like LINUX, Linux, or Linux.

3. Searching for a string in different files

Grep can also search for a string in multiple files using a single command line. The files in question can have different file extensions. For instance, the command can scan through files with a .txt, .php, or an .html extension

4. Search multiple files using the wildcard

When looking for a search string in multiple files of the same format, the wildcard is used in place of the file name separated by the file extension. For example, instead of using index.html on the command line, we use an asterisk (*) and the file extension.

The extension after the asterisk can be any file format. The above command displays the word Linux found on all html files.

5. Search and filter files

The command can be used to search and output files in a given format. If for instance, you want to troubleshoot your samba configuration file, found on the following path /etc/samba/smb.conf. You can output all the lines in this file by leaving out the commented lined by running

The –v option tells the command to print out all lines in the smb.conf file that do not match the criteria, in our case (print all lines that are not commented)

6. Display the number of lines before and after the search string

Different options are available and can be used in the format –A and –B as options. The two options display the matching line and the number of lines before and after the string.

The command uses the ifconfig command to display the Ethernet cable (eth0) configurations then redirect the result to the grep using the –A option to 4 lines coming after eth0. The second command using the –B option displays 2 lines after eth0.

7. Print the number of lines around a matching string

The grep –C option works the same way as the above command, but it will print the given number of lines before and after the expression.

This command will print out four lines before and after the loopback device lo

8. Count the number of matches to a particular query

The grep’s inbuilt command option allows you to get all the matches that are specific to what you are looking for. If you want to see all the interfaces on your machine use grep in this format

This command displays all IPv4 and IPv6 network interfaces

9. Display the file line number

You can use this command to display line numbers with a matching string when using the –n option. This is useful for debugging compilation errors

This line will show which line number “word” is found in the file.txt file.

10. Recursive search

When you are looking for a specific string in the current directory alongside all its subdirectories, using the –r option allows for recursive search.

The string function in all subdirectory of the current directory will be displayed.

11. Using grep command in unix/linux to search full words only

If you are looking for a specific word that may also be part of another sentence, you can use grep to force a selection that only forms the complete word.

The search will narrow down to the string “bio” and not biochemistry, biology, or biomedicine, etc. if such expressions exist in FileName.

12. Fast Grep (grep -F or fgrep)

This is also known as ‘fast grep’ or fixed string. It’s referred to as fast grep because it boasts of a better performance compared to grep and egrep. It drops regular expressions and looks for a distinct string pattern. It comes in handy when searching for unique static content in a precise and concise manner.

Usage

OR

For instance, file1.txt contains the following lines

To search the pattern “one and only” run

This will display Lines 1 and 3 only because they contain the search string “one and only”

Output

-b flag specifies the block number

Example

Output

-c flag counts the number of lines containing instances of the string pattern

For example

Output

13. Grep -o

Back to our file1.txt, If you want only to display the search string “one and only” run

Output

A similar command that gives the same output is

14. Search a string in Zipped file formats

Sometimes you may be forced to look for strings in a zipped document. Grep uses the following derivatives to handle such cases, the zgrep, zcat, and gzipped. All the derivatives take and use the same options as grep.

The output here will be the word error on the syslog.2.gz files.

15. Matching regular expression

This powerful feature helps when searching for all patterns that start and end with a particular string. For example to look for a file with a start line “start and ends with “ends” strings with anything in between the two strings use:

The result will be any file with the first and last lines being start and ends. Other options that can be used when looking for matching expressions are as listed below:

• ? The preceding item is optional and matched at most once.
• The preceding item will be matched zero or more times.
• + The preceding item will be matched one or more times.
• {n} The preceding item is matched exactly n times.
• {n,} The preceding item is matched n or more times.
• {,m} The preceding item is matched at most m times.
• {n,m} The preceding item is matched at least n times, but not more than m times.

16. Show the position of the matching string

Grep can be used to show line position where the particular match is found using this format, assuming we already have our file.txt with some content such as ABCDEFGHIJKL

Output

The output above is not the actual line number but the byte offset which counts from 0.

17. Show file names with matching string pattern

We use the grep –l option to show the given pattern. When dealing with multiple files as input with the grep command in unix/linux. This is very useful when looking for some particular notes in your directory.

This command will list all files with “string “on it.

18. Counting the number of matches

When there is a need to count the number of lines matching the string pattern use the –c option.

When you add the option –v to the above command, it will give the number of lines that do not match a given pattern.

Show the number of lines that do not match all given patterns on the command line. For example, a file with the strings ABCDEFGHIJKL when issued with the command below:

This returns BCDFHIJKL
This command can further be modified to give case-insensitive results using the –vi option.

19. Highlight search Strings

The option to highlight search output is made possible when you use the –color option. In some cases, you may have to set the environment variables GREP_OPTIONS as indicated below

The “color” attribute can take any color codes supported by the system.
The command is used as follows:

All the results (Linux in this case) searches will be highlighted in a different color.

20. Display all lines ending with a specific pattern

The $ symbol is used by appending it to the search string on the command line as shown:

All lines in the passwd file ending with “string” will be shown.

21. Display lines starting with a specified string

The ^ symbol is appended to the string to give the desired output

The caret (^) symbol indicates the beginning of the line when used in Linux commands. The output will be all lines starting with the word “string.”

22. Filter specific files

Grep can also be used when you need to get particular files as your output. If for instance, your folder has many images in different formats and you only need a list of all the GIFs from a specified image folder, you can use the find command and channel the output through grep

The above command outputs all gif files piped to grep that will filter out specific images from FolderName and then re-directed through the –vi option to filter out file names “string.”

23. Using Grep and Pipes to Direct Output

If you want to see the devices connected to your machine, you can use grep and pipes in a different format as shown below

The dmesg command displays drive the message or info that matches the drive names given in ‘(s|h)d[a-z]’

24. Display the CPU model name

The cat command is used to create or view files. The  command below uses cat to view cpuinfo and later filter the output using grep where ‘String’ is the search term

# cat /proc/cpuinfo | grep -i ‘String’

For example, to display all attributes in /proc/cpuinfo with ‘cpu’ execute

Output

25.  To confirm if PATH is exported

If you want to confirm if PATH has successfully been exported to ~/.bashrc we use the command export that will search for lines with the string PATH as follows:

# grep export ~/.bashrc | grep ‘\<PATH’

The Common Linux Pipes used by Grep

Grep commands are in most cases used alongside shell pipes used to connect one command output to another without the need of a temporary file. The pipe syntax takes the form:

Command 1 | command 2 or command 1 | command 2 | command N…

In most cases, such redirection is simply interpreted as

“get data” | “verify data” | “process data” | “format data” > OutputData.file

The connection between one command to the next is referred to as a pipe symbolized by a vertical (|) bar. The command direction takes one direction only.

Using GREP Environment Variables

Environmental variables control the GREP behavior. Some of these variables are picked automatically upon installation of the operating system while others have to be defined to suit a particular environment.

GREP_COLOUR
Specifies the color used when the highlight command is invoked. Using GREP_COLORS too also has the same effect that also supports many options

GREP_OPTIONS                                                                                                        This option gives you an option of specifying default options for a particular session or throughout the system. The defined option will override any explicit option.

Conclusion

This article is not the end of grep command in Unix/Linux, we tried as much as possible to include the most common commands you are likely to use. The important thing is to read and understand the command usage and adapt it to serve your purposes. If you are on your command line type grep –-help for more options and usage.

Continue Reading

Trending

Copyright © 2019 LinuxTeacher.com