Linux Guides, Tips and Tutorials | LinuxScrew https://www.linuxscrew.com LinuxScrew is a Linux resource that contains many useful guides on Linux, programming, networking, and more. Tue, 08 Jun 2021 13:28:21 +0000 en-US hourly 1 https://wordpress.org/?v=5.7.2 https://www.linuxscrew.com/wp-content/uploads/2020/10/favicon-7-48x48.png Linux Guides, Tips and Tutorials | LinuxScrew https://www.linuxscrew.com 32 32 Bash/Shell Script to Send Email In Linux – Howto, Example https://www.linuxscrew.com/bash-send-email https://www.linuxscrew.com/bash-send-email#respond Sun, 20 Jun 2021 09:22:10 +0000 https://www.linuxscrew.com/?p=7730 This article will show you several ways to send an email from the Linux command line/shell – as well as from Bash/Shell scripts. Why would you want to send an email from the command line? Probably not to communicate – most people use an email client with a nice user interface to send messages to… Read More »Bash/Shell Script to Send Email In Linux – Howto, Example

View the original article from LinuxScrew here: Bash/Shell Script to Send Email In Linux – Howto, Example

]]>
This article will show you several ways to send an email from the Linux command line/shell – as well as from Bash/Shell scripts.

Why would you want to send an email from the command line? Probably not to communicate – most people use an email client with a nice user interface to send messages to each other day to day – but you may want to have your computer send an email notification when a task completes or when an event occurs.

Such email alerts are commonly used to alert on low disk space or notify someone if an error occurs, power is lost – you could even write a notification to provide you a daily summary of new user signups to your latest app. Here are several tools that will let you do this – with examples.

A Note on Sending Mail

The examples in this article will all assume you are using an external SMTP server to send mail. This may be a dedicated email sending service like Amazon SES or MailGun, or you may send emails from your online email provider (Gmail, Outlook.com) using the SMTP details they provide.

This article does not cover setting up and sending mail directly from your own SMTP host for one simple reason – your messages are likely to be blocked if they are coming from a residential IP address, and you will have a hard time troubleshooting whether your email alerts are working correctly and being blocked, or just not working.

Choosing the Right Program

Many software packages can send email – a large number. I’m not going to try and cover all of them – you’re here looking for something that just works, so…

MSMTP is an ideal tool for this job, so I’ll keep the focus of this article on how to use that program.

Previously, SSMTP was my preferred choice, but the development of that package has stopped – MSMTP is a good replacement.

Other options include the sendmailmail, and mutt commands. All will work, but MSMTP is easy to use and configure and can maintain an independent configuration that won’t interfere with system mail.

Using MSMTP to Send Email

MSMTP is a program that sends email (and only) sends email – making it perfect for sending emails from Bash scripts.

Once you have installed MSMTP, you can view the user manual by running:

man msmtp

Install MSMTP

On Debian/Ubuntu-based systems, run the following commands to install the required MSMTP package and the ca-certificates package if it isn’t installed already:

sudo apt update
sudo apt install msmtp ca-certificates

The sudo command is used to run commands with root/administrative privileges throughout this article.

Configure MSMTP

MSMTP supports per-user configuration or a global system configuration – we’ll set this up with a global configuration so that all services can use MSMTP to send email.

MSMTP comes with an example configuration file we can use as a template – we’ll need to make a copy of it in the /etc/ folder for use:

sudo cp /usr/share/doc/msmtp/examples/msmtprc-system.example /etc/msmtprc

Edit the configuration file using the nano text editor:

sudo nano /etc/msmtprc

Now, you can fill in the details of the SMTP server you will use to send email. You can define several mail accounts if you wish to send from different servers or addresses.

Below is a sample configuration with two Gmail addresses:

# Set default values for all following accounts.
defaults
auth           on
tls            on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        ~/.msmtp.log

# Gmail 1
account        gmail1
host           smtp.gmail.com
port           587
from           username1@gmail.com
user           username1
password       password1

# Gmail 2
account        gmail1
host           smtp.gmail.com
port           587
from           username2@gmail.com
user           username2
password       password2


# Set a default account
account default : gmail1

Save the file – MSMTP is ready to use.

Send an Email

Once MSMTP is set up, you’re ready to go. No additional software is needed to send email from MSMTP – you can simply use the printf command to construct your email and pipe it to the msmtp command:

printf "Subject: Testing\nHello there!." | msmtp -a gmail2 recipient@example.com

“Subject: Testing\nHello there!.” – This is the email which will be sent. A subject is defined using Subject: followed by the subject text. \n defines a New Line, which is then followed by the email body text. Additional \n newlines can be added where required to construct a plain text message with formatting.

The -a option is used to set which email account the email will be sent from – if it is not set, the default will be used.

Send an Email with an Attachment using Mutt

Sending an email with an attachment is a bit trickier – additional software is needed to make it easier to do. mutt is an email client which adds this functionality with minimal fuss for use in scripts.

Install it by running:

sudo apt install mutt

mutt may install the Postfix mail transfer agent as a dependency – it will ask for a mail configuration. You can safely choose No configuration – we do not need postfix to be configured. As mentioned earlier in this article, we do not want to send mail directly from this system as it’s likely to not reach its destination due to spam filtering.

Like MSMTP, mutt has per user and global configurations. We’ll use a global configuration so that all users/services can send mail with attachments. Create and edit the file using the nano text editor by running:

nano /etc/muttrc

Enter the below configuration (with values replaced with those from your own mail configuration):

set sendmail="/usr/bin/msmtp"
set use_from=yes
set realname="Your Name"
set from=username1@gmail.com
set envelope_from=yes

mutt is now configured and can be used to send an email with an attachment:

mutt -a attachment.txt -s "My Subject" -- recipient@example.com < "Email message body"

Per-User vs. Global Configuration

Above, global configurations have been defined. If you want the configuration to only apply to certain users – so that each user can send only from their own user account, for example – place the configuration in the following files in the users home directory instead:

~/.msmtprc
~/.muttrc

View the original article from LinuxScrew here: Bash/Shell Script to Send Email In Linux – Howto, Example

]]>
https://www.linuxscrew.com/bash-send-email/feed 0
How to Format a USB Drive From the Linux Shell https://www.linuxscrew.com/linux-format-usb https://www.linuxscrew.com/linux-format-usb#respond Sat, 19 Jun 2021 09:22:08 +0000 https://www.linuxscrew.com/?p=7736 This article will show you how to format a USB stick or external USB hard drive from the Linux command line/shell for FAT, NTFS, and EXT file systems. Plug In the Drive The first step – plug in your USB stick or external hard drive and give it a few moments to be detected. Find… Read More »How to Format a USB Drive From the Linux Shell

View the original article from LinuxScrew here: How to Format a USB Drive From the Linux Shell

]]>
This article will show you how to format a USB stick or external USB hard drive from the Linux command line/shell for FAT, NTFS, and EXT file systems.

Plug In the Drive

The first step – plug in your USB stick or external hard drive and give it a few moments to be detected.

Find the Drive

Next, find the drive you just plugged in using the fdisk command to list (-l) the attached storage devices:

sudo fdisk -l

We’ll be using the sudo command frequently – many of these tasks require administrative privileges.

The fdisk command will output a list of storage devices attached to your system. Among them (hopefully last in the list to make it easy to find) will be the device you just plugged in:

Disk /dev/sdb: 29.26 GiB, 31406948352 bytes, 61341696 sectors
Disk model: Cruzer Blade    
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xfdb38d34

Device     Boot Start      End  Sectors  Size Id Type
/dev/sdb1        2048 61341695 61339648 29.3G  c W95 FAT32 (LBA)

Above, you can see the device /dev/sdb (the physical USB drive) and /dev/sdb1 – a FAT partition on that drive.

The device names sdb/sdb1 may differ on your system!

Make Sure the Drive Isn’t Mounted

You can’t format a drive that is in use, so the drive must be unmounted from the file system. Some systems will have mounted the drive automatically, and some will not have.

sudo umount /dev/sdb1

The above command will unmount /dev/sdb1.

Format the Drive

The mkfs set of commands will create an empty file system on a given device. Not all filesystems are supported on all operating systems, so choose one that works for you.

Be warned – all files will be removed – so make sure you’re sure you want to remove everything on the drive and that you use the correct path to the device to avoid formatting the wrong drive.

Format for EXT4 Filesystem

The following command will format using the EXT4 filesystem for use on Linux Systems:

sudo mkfs.ext4 /dev/sdb1

Format for FAT/vFAT Filesystem

The following command will format using the FAT filesystem for use in Linux, Windows, and macOS:

sudo mkfs.vfat /dev/sdb1

Format for NTFS Filesystem

The following command will format using the NTFS Filesystem for use on Windows and some supported Linux distributions:

sudo mkfs.ntfs /dev/sdb1

Looking to mount your newly formatted USB stick or drive? Here’s how.

View the original article from LinuxScrew here: How to Format a USB Drive From the Linux Shell

]]>
https://www.linuxscrew.com/linux-format-usb/feed 0
Mount a USB Stick/Drive in Linux [HowTo, Tutorial] https://www.linuxscrew.com/linux-mount-usb https://www.linuxscrew.com/linux-mount-usb#respond Fri, 18 Jun 2021 09:22:07 +0000 https://www.linuxscrew.com/?p=7738 This tutorial will show you how to mount and access a USB stick or external USB hard drive on Linux. Most desktop Linux distributions will automatically mount USB drives show them in their file explorer, but lightweight and server distributions may not include this functionality – either because it’s considered unnecessary or because the typical… Read More »Mount a USB Stick/Drive in Linux [HowTo, Tutorial]

View the original article from LinuxScrew here: Mount a USB Stick/Drive in Linux [HowTo, Tutorial]

]]>
This tutorial will show you how to mount and access a USB stick or external USB hard drive on Linux.

Most desktop Linux distributions will automatically mount USB drives show them in their file explorer, but lightweight and server distributions may not include this functionality – either because it’s considered unnecessary or because the typical user of said distribution wants to be able to do manage those tasks themselves.

Modern Linux distributions should all include drivers for USB sticks and external drives, so it’s just a matter of mounting them at a location in the file system so that they can be accessed. Here’s how to do it.

Plug In the Drive

The first step – plug in your USB stick or external hard drive and give it a few moments to be detected.

Find the Drive

Next, find the drive you just plugged in using the fdisk command to list (-l) the attached storage devices:

sudo fdisk -l

We’ll be using the sudo command frequently – many of these tasks require administrative privileges.

The fdisk command will output a list of storage devices attached to your system. Among them (hopefully last in the list to make it easy to find) will be the device you just plugged in:

Disk /dev/sdb: 29.26 GiB, 31406948352 bytes, 61341696 sectors
Disk model: Cruzer Blade    
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xfdb38d34

Device     Boot Start      End  Sectors  Size Id Type
/dev/sdb1        2048 61341695 61339648 29.3G  c W95 FAT32 (LBA)

Above, you can see the device /dev/sdb (the physical USB drive) and /dev/sdb1 – a FAT partition on that drive.

The device names sdb/sdb1 may differ on your system!

Create Mount Point

Before you can mount the drive for use, you’ll need a location for the drive to be accessed from – an empty folder:

sudo mkdir /media/usb1

The /media/ directory is commonly used for removable media – so I’ve created a folder in it for this USB drive to be mounted under.

Mount the Drive

The mount command will mount a given storage device to a given directory:

sudo mount /dev/sdb1 /media/usb1

The above command mounts the FAT partition on the USB stick (/dev/sdb1) to the /media/usb1 directory created above

Check Mounted Volumes

You can check whether the drive has mounted successfully by piping the output of the mount command to the grep command and searching for the name of your USB device:

mount | grep sdb1

Use the Drive

With the drive mounted, you can simply use the files on the drive as you would any other path on your file system:

touch /media/usb1/myFile.txt

The above command would create a new file on the USB drive called myFile.txt.

Unmount the Drive

The umount command will unmount a drive so it can be safely disconnected:

sudo umount /dev/sdb1

Simply supply the device path to the umount command, and any mount points for it will be unmounted.

Mount Automatically on Boot

If your drive is going to be staying attached to your system permanently, you may wish to have it mount automatically:

First, find the UUID of your disk – this unique identifier will persist reboots. List the UUID for the disks by running:

ls -l /dev/disk/by-uuid/*

Make a note of the entry for your USB device, in my case:

/dev/disk/by-uuid/87CD-13C2 -> ../../sdb1

And then edit your fstab file to add a record for automatic mounting:

nano /etc/fstab

Add a line like the following:

/dev/disk/by-uuid/87CD-13C2    /media/usb1         vfat   0   0

… with the UUID for your own USB device. You may also have to replace the vfat bit if you are not using a FAT-formatted drive.

To mount all unmounted devices from fstab without rebooting run:

mount -a

Check out our article on formatting USB drives here.

View the original article from LinuxScrew here: Mount a USB Stick/Drive in Linux [HowTo, Tutorial]

]]>
https://www.linuxscrew.com/linux-mount-usb/feed 0
Linux vs Windows – The Practical Differences in 2021 https://www.linuxscrew.com/linux-vs-windows https://www.linuxscrew.com/linux-vs-windows#respond Thu, 17 Jun 2021 09:22:06 +0000 https://www.linuxscrew.com/?p=7749 Are you a Windows user looking for reasons to give Linux a go? This article explores why you might make Linux your operating system of choice over Windows. Or the opposite, if you’re into that sort of thing. First, let’s look at what makes Windows Windows and why people use it. Windows For better or worse,… Read More »Linux vs Windows – The Practical Differences in 2021

View the original article from LinuxScrew here: Linux vs Windows – The Practical Differences in 2021

]]>
Are you a Windows user looking for reasons to give Linux a go? This article explores why you might make Linux your operating system of choice over Windows. Or the opposite, if you’re into that sort of thing.

First, let’s look at what makes Windows Windows and why people use it.

Windows

For better or worse, Windows is the most popular operating system for desktop computers – and has been for decades.

Being the most popular operating system for so long, lots of software has been written for it. Most importantly, Microsoft’s own Office suite and Adobe’s creative suite run on Windows and have become the industry standard for their categories.

However, that popularity has a downside – Windows is the most common target for malware and has historically been vulnerable because of its focus on backward compatibility – keeping old, broken parts of the system alive just so that old business applications written decades ago can be run on the platform (looking at you, Internet Explorer).

Windows is a paid, closed source, commercial product. The source code is a (somewhat) closely kept Microsoft secret – so if there’s a security hole, the only way it gets fixed is if someone in Microsoft spots it or a nefarious hacker finds it first.

Why Would You Use Windows?

Games. Microsoft Office. Adobe Suite. These are the three demons you must slay to leave the Windows world.

It’s not all bad, though. Windows has come a long way and is a perfectly fine general use desktop operating system. If you’re looking for more advanced tools, Windows can now run Linux software via the Windows Subsystem for Linux, too.

Obviously, I prefer Linux, but it’s worth pointing out that Windows is fit for purpose – no need to drag your Windows machines to the curb unnecessarily.

Linux (Yay!)

Rather than repeat myself, check out our article on why you should use Linux in 2021.

To sum it up, Linux is the most popular operating system for servers (and mobile devices – via Android, which is built on Linux). That popularity in the server category has made it popular with computer enthusiasts and developers. It’s got lots of free software, which is often just as good as those big three mentioned above.

Why Would You Use Linux Instead of windows?

Security. Stability. Price (it’s free).

Linux provides a rock-solid foundation for developing or hosting your own software in a variety of programming languages.

Like Windows, Linux also has great software (if you aren’t worried about Microsoft Office and Adobe stuff).

Linux has started growing as a gaming platform and will continue to do so – check out our article on gaming on Linux.

If you’re running an old version of Windows (any version that isn’t Windows 10) – your system is out of date, no longer receives security patches, and is woefully insecure.

Switching to Linux is a free upgrade to an OS that isn’t full of yawning security holes.

View the original article from LinuxScrew here: Linux vs Windows – The Practical Differences in 2021

]]>
https://www.linuxscrew.com/linux-vs-windows/feed 0
How To Compare Arrays in JavaScript, With Examples https://www.linuxscrew.com/javascript-compare-arrays https://www.linuxscrew.com/javascript-compare-arrays#respond Wed, 16 Jun 2021 09:22:05 +0000 https://www.linuxscrew.com/?p=7754 This article will show you how to compare arrays in JavaScript and provides some ready-to-use functions to do so. We’ve already covered a bit on how to use arrays in JavaScript: Looping over Array using JavaScript forEach(), With Examples Array slice() Method in JavaScript, with Examples() Check Array Contains a Value in JavaScript, with Examples… Read More »How To Compare Arrays in JavaScript, With Examples

View the original article from LinuxScrew here: How To Compare Arrays in JavaScript, With Examples

]]>
This article will show you how to compare arrays in JavaScript and provides some ready-to-use functions to do so.

We’ve already covered a bit on how to use arrays in JavaScript:

What is an Array?

An array is a type of JavaScript variable that can hold other variables, or references to other variables, in a list at a certain position.

Comparing Arrays in JavaScript

As elements in an array have both a value and an index (or position), you will need to decide how you wish to compare them. Here are the options with code examples.

Checking if Arrays Contain the Same Values, Regardless of Order

Note that this will not work well if there are duplicate values in the array – only the presence of a value in each array can be compared, not how many times it appears, as the position of each element is not checked.

The following function will check whether two arrays contain the same values, regardless of frequency or position.

function compareArrayValues(array1, array2){
    
    # Get only the unique values in each array
    # This uses the new ES6 Set feature - a Set contains only unique values, so by converting an array to a Set and back, only the unique values are kept
    # the ellipsis (...) expands the values of the Set, which is faster to type than a foreach loop to add each value to the array
    array1 = [...new Set(array1)];
    array2 = [...new Set(array2)];

    # Sort the arrays so the values are in order and can be compared:
    array1.sort();
    array2.sort();

    # The arrays can now be compared directly.  A cheeky shortcut to do this is to convert them to a JSON string and compare those - if the strings match, the arrays are the same
    # This is again much faster than iterating through the array and comparing each value
    return JSON.stringify(array1) === JSON.stringify(array2);
}

This function will return TRUE if the arrays contain the same values or FALSE if they do not.

Checking if Arrays Contain the Same Values, In The Same Order

The following function compares the arrays directly – they must be completely identical:

function compareArrays(array1, array2){
    
    # The arrays can be compared as-is as we want both the value and position of each element to be checked.  A cheeky shortcut to do this is to convert them to a JSON string and compare those - if the strings match, the arrays are the same
    # This is much faster than iterating through the array and comparing each value
    return JSON.stringify(array1) === JSON.stringify(array2);
}

This function will return TRUE if the arrays are exactly the same or FALSE if they are not.

Finding Values in an Array that Aren’t in Another

Modern versions of JavaScript since the ECMA2015 release (which should be by now widely supported) provide functions for easy filtering of arrays to find differences between them.

The below example will take the elements in array1 that are not in array2 and create a new differences array with them.

var differences = array1.filter(e => array2.indexOf(e) < 0);

How does this work?

array1 is being filtered to only include values that do not appear in array2. Whether a value appears in array2 is determined by whether it has a valid index (an index greater than 0 or not).

View the original article from LinuxScrew here: How To Compare Arrays in JavaScript, With Examples

]]>
https://www.linuxscrew.com/javascript-compare-arrays/feed 0
JavaScript instanceof Operator – What it Does, How to Use It https://www.linuxscrew.com/javascript-instanceof https://www.linuxscrew.com/javascript-instanceof#respond Tue, 15 Jun 2021 09:22:03 +0000 https://www.linuxscrew.com/?p=7760 This article will explain what the JavaScript instanceof operator does and how it can be used. Examples provided. What does instanceof do? The instanceof operator returns TRUE or FALSE depending on whether a given value or variable is of a certain type or class – it checks whether a value is an instance of a given object class or type. The purpose of instanceof may seem confusing –… Read More »JavaScript instanceof Operator – What it Does, How to Use It

View the original article from LinuxScrew here: JavaScript instanceof Operator – What it Does, How to Use It

]]>
This article will explain what the JavaScript instanceof operator does and how it can be used. Examples provided.

What does instanceof do?

The instanceof operator returns TRUE or FALSE depending on whether a given value or variable is of a certain type or class – it checks whether a value is an instance of a given object class or type.

The purpose of instanceof may seem confusing – you already have typeof, so what do you need instanceof for?

typeof will simply return a string containing the name of the type or class of the variable. In contrast, instanceof will return a boolean value confirming whether a given variable matches a given class at a programmatic level.

What is a Type/Class?

A variable type determines what kind of data it can store and what can be done for it. A variable type is defined by its class – which is the code that defines what data can be stored and the functions and associated behavior.

For example, string typed variables are sequences of characters that can be joined and split (think words and sentences), while numeric typed variables contain numeric values which can be used in arithmetic.

instanceof Syntax

The syntax for using instanceof is as follows:

OBJECT instanceof CONSTRUCTOR

Note that:

  • OBJECT is the variable or value you want to check
  • CONSTRUCTOR is the name of the class you want to check whether OBJECT is an instance of
  • A boolean TRUE or FALSE value will be returned
  • instanceof checks the entire prototype chain of the OBJECT
    • This means that instanceof can return a positive result for two different CONSTRUCTORs if one constructor is derived from the other

instanceof JavaScript Examples

This example creates a Person class, and then an object is created using this class. instanceof is then used to confirm that the created object is of the Person class.

// Define a constructor which creates an object of the Person class - containing a person's details
function Person(name, age, height) {
    this.name = name;
    this.age = age;
    this.height = height;
}

// Define a new person using the above constructor
var jim = new Person('Jim', 21, 182);

// Check whether the jim variable is an instance of the Person class
console.log(jim instanceof Person);
// Will return true as jim is an instance of the Person class

// Check whether the jim variable is of the Object class 
console.log(jim instanceof Object);
// Will also return true - JavaScript objects are an inheritable class which other objects are built on

console.log(jim instanceof String);
// Will return false as the jim variable is not of the String type

Note that the jim object is considered an instance of both the Person and Object classes – as the Person class extends the Object class. In most cases, custom classes in JavaScript will extend the Object class when created unless otherwise specified.

For more examples on how instanceof can be used, check out the Mozilla developer documentation.

View the original article from LinuxScrew here: JavaScript instanceof Operator – What it Does, How to Use It

]]>
https://www.linuxscrew.com/javascript-instanceof/feed 0
Refresh or Redirect a Page using PHP, With Examples https://www.linuxscrew.com/php-refresh-page https://www.linuxscrew.com/php-refresh-page#respond Mon, 14 Jun 2021 09:22:03 +0000 https://www.linuxscrew.com/?p=7765 This article will show you how to refresh a web page in the browser using the PHP programming language. It’s sometimes necessary to set a page to reload automatically, usually at some interval, to keep the page updated with changing information. For example, you may have a scoreboard application that is displayed in a web… Read More »Refresh or Redirect a Page using PHP, With Examples

View the original article from LinuxScrew here: Refresh or Redirect a Page using PHP, With Examples

]]>
This article will show you how to refresh a web page in the browser using the PHP programming language.

It’s sometimes necessary to set a page to reload automatically, usually at some interval, to keep the page updated with changing information.

For example, you may have a scoreboard application that is displayed in a web browser on a projector and wish to have it periodically refresh to keep the displayed scores up to date with those stored.

Periodic refreshing is also used to redirect to a different page at a given interval, which could be used to emulate slideshow functionality for digital signage.

Refreshing the Page Using PHP

The PHP header function is used to set HTTP request headers – bits of information invisible to the end-user which tell the web browser about the data it is receiving.

The Refresh header tells the browser to refresh the page after a given number of seconds:

<?php
header("Refresh:0");
?>

Above, the page is refreshed immediately, as 0 seconds is specified. To refresh after 3 seconds, you would use:

<?php
header("Refresh:3");
?>

The Refresh header is not an official specification – most if not all browsers do heed it, but it is worth testing with your intended audience.

Redirecting to a Different Address Using PHP

The Refresh header also accepts an optional url if you wish to redirect to another page:

header("Refresh:0; url=another-page.php");

Above, when the PHP is executed during page load, it will immediately redirect to the another-page.php. Any kind of URL can be supplied – it doesn’t have to be a local file on your server.

It Could be Better to use JavaScript

Refreshing the page using PHP can be less than ideal. The user will have no interaction or ability to interrupt the refresh request, and you cannot perform any client-side operations as they may take longer than you expect – meaning your page is refreshed before tasks are complete and unexpected behavior may result.

It could be better to use JavaScript for this task – we’ve covered it in the below article.

How to Refresh the Page in JavaScript using location.reload(), With Examples

Refreshing is a client-side operation. JavaScript is the client-side scripting language used by web browsers, so it can be better to do it this way rather than using server-side PHP to dictate what the client should do.

PHP might be preferable if you want search spiders such as Googlebot to crawl your redirects easily.

View the original article from LinuxScrew here: Refresh or Redirect a Page using PHP, With Examples

]]>
https://www.linuxscrew.com/php-refresh-page/feed 0
How to Get CPU Information on Linux, With Examples https://www.linuxscrew.com/linux-cpu-info https://www.linuxscrew.com/linux-cpu-info#respond Sun, 13 Jun 2021 09:22:03 +0000 https://www.linuxscrew.com/?p=7769 Here’s how to display the CPU info for your computer on Linux from the Linux command line. The CPU (Central Processing Unit) in your computer does all of the number crunching and processing and logic that your computer needs to do to, well, compute. It’s the brains of the whole operation. The type of CPU,… Read More »How to Get CPU Information on Linux, With Examples

View the original article from LinuxScrew here: How to Get CPU Information on Linux, With Examples

]]>
Here’s how to display the CPU info for your computer on Linux from the Linux command line.

The CPU (Central Processing Unit) in your computer does all of the number crunching and processing and logic that your computer needs to do to, well, compute. It’s the brains of the whole operation.

The type of CPU, how old it is, and how fast it is determines how responsive your computer is and how quickly it can do things.

CPU Info From /proc/cpuinfo

One of the core concepts which Linux (generally) adheres to is that all aspects of the computer system are represented in the filesystem – including hardware.

The /proc directory is a virtual filesystem that contains information about system resources. This includes information about the CPU.

More information can be found by running:

man proc

..to view the user manual.

So, to view the information on the CPU installed on your system, you simply need to view the file which contains it:

cat /proc/cpuinfo

The cat command is used to view the contents of the file stored at /proc/cpuinfo

The above command will output something like the following:

processor	: 0
vendor_id	: GenuineIntel
cpu family	: 6
model		: 142
model name	: Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
stepping	: 9
microcode	: 0xea
cpu MHz		: 2304.000
cache size	: 4096 KB
physical id	: 0
siblings	: 2
core id		: 0
cpu cores	: 2
apicid		: 0
initial apicid	: 0
fpu		: yes
fpu_exception	: yes
cpuid level	: 22
wp		: yes
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm constant_tsc nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid rdseed adx smap clflushopt xsaveopt xsavec dtherm arat pln pts
bugs		: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs itlb_multihit srbds
bogomips	: 4608.00
clflush size	: 64
cache_alignment	: 64
address sizes	: 36 bits physical, 48 bits virtual
power management:

processor	: 1
vendor_id	: GenuineIntel
cpu family	: 6
model		: 142
model name	: Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
stepping	: 9
microcode	: 0xea
cpu MHz		: 2304.000
cache size	: 4096 KB
physical id	: 0
siblings	: 2
core id		: 1
cpu cores	: 2
apicid		: 1
initial apicid	: 1
fpu		: yes
fpu_exception	: yes
cpuid level	: 22
wp		: yes
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm constant_tsc nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid rdseed adx smap clflushopt xsaveopt xsavec dtherm arat pln pts
bugs		: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs itlb_multihit srbds
bogomips	: 4608.00
clflush size	: 64
cache_alignment	: 64
address sizes	: 36 bits physical, 48 bits virtual
power management:

My computer has two processor cores, so the information for the two processors is listed.

You probably only really want the model name of your CPU so you can compare it with others – you can limit this output by searching the output with the grep command:

grep -m 1 'model name' /proc/cpuinfo

Which will output something like:

model name	: Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz

The -m 1 option supplied to grep will return only the model of one of the CPUs – otherwise, you’ll get the model for each core on a multi-core CPU, and it’s almost certain that they will be the same.

CPU Info From lscpu

The lscpu command can also be used to display information about your CPU. Simply run:

lscpu

And you’ll get output that looks something like this:

Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   36 bits physical, 48 bits virtual
CPU(s):                          2
On-line CPU(s) list:             0,1
Thread(s) per core:              1
Core(s) per socket:              2
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           142
Model name:                      Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
Stepping:                        9
CPU MHz:                         2304.000
BogoMIPS:                        4608.00
Hypervisor vendor:               KVM
Virtualisation type:             full
L1d cache:                       64 KiB
L1i cache:                       64 KiB
L2 cache:                        512 KiB
L3 cache:                        4 MiB
NUMA node0 CPU(s):               0,1
Vulnerability Itlb multihit:     KVM: Mitigation: VMX unsupported
Vulnerability L1tf:              Mitigation; PTE Inversion
Vulnerability Mds:               Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Spec store bypass: Vulnerable
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Full generic retpoline, STIBP disabled, RSB filling
Vulnerability Srbds:             Unknown: Dependent on hypervisor status
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 
                                ss ht syscall nx rdtscp lm constant_tsc nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmul
                                qdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rd
                                rand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bm
                                i2 invpcid rdseed adx smap clflushopt xsaveopt xsavec dtherm arat pln pts

This output is quite similar to that supplied by viewing the contents of /proc/cpuinfo – however it is not duplicated for each core.

View the original article from LinuxScrew here: How to Get CPU Information on Linux, With Examples

]]>
https://www.linuxscrew.com/linux-cpu-info/feed 0
List Running Processes in Linux with ps, top, or htop https://www.linuxscrew.com/linux-list-processes https://www.linuxscrew.com/linux-list-processes#respond Sat, 12 Jun 2021 09:22:01 +0000 https://www.linuxscrew.com/?p=7777 This article will show you how to list running processes in Linux using several tools. This will allow you to see what is running and how your system resources are being consumed. It’s helpful to see what resources are in use by what process to diagnose slow systems. This information can be used to determine… Read More »List Running Processes in Linux with ps, top, or htop

View the original article from LinuxScrew here: List Running Processes in Linux with ps, top, or htop

]]>
This article will show you how to list running processes in Linux using several tools. This will allow you to see what is running and how your system resources are being consumed.

It’s helpful to see what resources are in use by what process to diagnose slow systems. This information can be used to determine whether you need to purchase more memory (RAM), a faster processor, or whether an application or service on your computer is misconfigured and using more resources than it should.

What is a Process?

process is an application running on your system. It could be a web browser that you can see running on your desktop, or it could be a file server running in the background that isn’t something with which you generally interact directly.

Processes consume resources – memory and processing time (as well as storage and networking resources if the application requires them), which they use to perform whatever task they were written to do.

The below commands list these running processes and the resources which they are using.

The ps Command

The ps (Process Status) lists the status of running processes (funnily enough). Run it with the default options by executing:

ps

By default, ps will list processes for the current terminal session – it will not show processes from other sessions or other users other than the one currently logged in.

To view all running processes for user users on the system:

ps aux

The aux option combines several options – a to show processes for all users, u to output additional info like CPU and memory usage, and x to list background processes not executed from the terminal.

You can view the full user manual for the ps command by running:

man ps

The top Command

The top command can be used to find resource-hungry processes – it provides an automatically updated display with processes in order of how much of the system resources they are using up.

Simply run:

top

To run it.

Rather than passing options to top, when top is running, you can press various keys on the keyboard to change how the data is displayed and sorted on the screen.

Hotkey
c Display the absolute path to the processes executable
d Changes the refresh interval – the rate at which the top screen is updated
h Show help
k Kill process
M Sorts by memory usage
N Sorts by PID (Process ID)
r Changes the process priority
z Displays process list in color
q Quit

Watch out! The above commands are case-sensitive.

Some of these commands may not be supported on your system if you are not running as root or using the sudo command.

You can view the full user manual for the top command by running:

man top

The htop Command

htop is just like the top command, but it has some extra features to make it easier to use.

You can scroll around to view the full list or use the mouse to navigate.

htop may not be installed by default in your Linux distribution.

If you’re on Ubuntu, it can be quickly installed by running:

sudo apt install htop

…and most other Linux distributions should have htop available in their package repositories.

Once installed, simply run:

htop

…to launch htop. Like top, it contains keyboard shortcuts to navigate, sort, and manage the running processes:

Hotkey
F1 Show help
F2 Show setup
F3 Search
F4 Filter processes by name
F5 Display tree view
F6 Sort processes by column
F7 Decrease process priority
F8 Increase process priority
F9 Kill process

You can view the full user manual for the htop command by running:

man htop

 

View the original article from LinuxScrew here: List Running Processes in Linux with ps, top, or htop

]]>
https://www.linuxscrew.com/linux-list-processes/feed 0
tee Command in Linux – Split Shell Output [Examples] https://www.linuxscrew.com/linux-tee https://www.linuxscrew.com/linux-tee#respond Fri, 11 Jun 2021 09:21:58 +0000 https://www.linuxscrew.com/?p=7779 The tee command in the Linux Shell/command line splits the output of an application – sending output to both a file and STDOUT (the console or another application). Here’s how to use it. The tee command is named for a T-splitter used in plumbing – a pipe that redirects water from a single source in two directions. tee Command… Read More »tee Command in Linux – Split Shell Output [Examples]

View the original article from LinuxScrew here: tee Command in Linux – Split Shell Output [Examples]

]]>
The tee command in the Linux Shell/command line splits the output of an application – sending output to both a file and STDOUT (the console or another application). Here’s how to use it.

The tee command is named for a T-splitter used in plumbing – a pipe that redirects water from a single source in two directions.

tee Command Syntax

tee is a command with a simple purpose and simple syntax:

tee OPTIONS FILE

Note that:

  • OPTIONS is a list of options from the below table
  • FILE is the path to the file you wish the output to be saved
  • Input needs to be piped or redirected to tee – otherwise, it has nothing to work with
  • tee will output the data provided to it both to the FILE specified as well as STDOUT (standard output)

Options

Here are the most commonly used options for the tee command:

-a, –append Append to the given FILEs, do not overwrite
-i, –ignore-interrupts Ignore interrupt signals

For more options, including how to diagnose errors, you can view the user manual by running:

man tee

tee Command Examples

Here are some simple examples of how tee can be used.

All of these examples use the echo command, which simply outputs the text supplied to it.

View and Save the Output from a Command to a New File

The output of the echo command will be piped to tee, which will save it to a file as well as outputting to the console:

echo "hello!" | tee hello.txt

If the file hello.txt exists, it will be overwritten.

View and save the Output from a Command to an Existing File

This example does the same as above, but it will append to the end of an existing file rather than overwriting it:

echo "hello again!" | tee -a hello.txt

Save or Append Output to Multiple Files

Multiple files can be specified, separated by spaces:

echo "hello several files!" | tee hello1.txt hello2.txt hello3.txt

Redirect/Pipe tee Output

The standard output of tee can be piped and redirected. The below example will save the output of echo to hello.txt. The output will then be passed to the grep command rather than output to the console:

echo "hello!" | tee hello.txt | grep hello

For example’s sake, the grep command (which is used for searching text input) simply searches the output from tee for the word “hello.”

Ignoring Interrupts

Ignoring interrupts (for example pressing CTRL + C to quit the command) can result in cleaner output from tee:

echo "hello!" | tee -i hello.txt

Using tee With sudo

The sudo command allows you to execute commands as the root user without logging in as root and is commonly used.

In the following snippet – sudo does not allow you to redirect the output of commands, as the sudo command itself does not perform the redirection as it appears before the redirection symbol (>):

sudo echo "hello!" > /root/hello.txt

…this will fail with a permission error because the /root directory requires root privileges, but the sudo command only applies these privileges to the echo command – not the redirection that comes afterward.

A trick to get around this is to use the tee command:

echo "hello!" | sudo tee /root/hello.txt

This will work because the output of the echo command is passed to tee, which is being run with administrative privileges via sudo – and tee saves the output.

View the original article from LinuxScrew here: tee Command in Linux – Split Shell Output [Examples]

]]>
https://www.linuxscrew.com/linux-tee/feed 0