Open gedit ~/.bashrc
file and add this script at the end of that (don't forget you have to add this script at the END of file or precisely after the prompt is set):
UNREAD="$(mailx <<< q | head -n2 | tail -n1 | cut -f4 -d" ")"
if [[ -n "$UNREAD" ]]; then
PS1="[Hi, alex. you have $UNREAD new mail(s)] $PS1"
fi
We wrote a variable that reads the count of unread mails using the mailx
program.
Explanation of command inside the variable:
mailx <<< q
We pass "q" to the stdin of mailx
so it quits immediately after the prompt is displayed.
head -n2 | tail -n1
from the first outputted 2 lines we only want the first line
cut -f4 -d" "
The mail count report goes:
/var/mail/alex: X messages Y unread
We want the fourth space-separated word (Y).
Now we have the number of unread messages inside the UNREAD variable, but it could be empty if there is no unread messages where the message would be shorter, i.e.:
/var/mail/alex: X messages
Then the command prompt will change and shows: "[Hi, alex. you have # new mail(s)]"
before the prompt. If you have not got any new mail then the command prompt will not change.
if [ -n "$UNREAD" ]; then
PS1="[Hi, alex. you have $UNREAD new mail(s)] $PS1"
fi
-n
flag with [ -n "$UNREAD" ]
checks if the length of UNREAD
is Not zero.
PS1
is defines your command prompt that configure into .bashrc
file in your home directory. This is what we open/edit this file. Then I edit that to include unread message count before your command prompt. See:
PS1="[Hi, alex. you have $UNREAD new mail(s)] $PS1"
Here's the screenshot if I have new mails:

And if I have not got any new mail:

That's it. Just copy and paste the script at the end of your ~/.bashrc
file.
mailcheck
ubuntu package – Janus Troelsen Apr 08 '20 at 03:30