How To Add Route on Linux

As a network engineer, you probably spend a lot of time thinking and planning your network infrastructure.

You plan how computers will be linked, physically using specific cables but also logically using routing tables.

When your network plan is built, you will have to implement every single link that you theorized on paper.

In some cases, if you are using Linux computers, you may have to add some routes in order to link it to other networks in your company.

Adding routes on Linux is extremely simple and costless : you can use the Network Manager daemon (if you are running a recent distribution) or the ifconfig one.

In this tutorial, you will learn how you can easily add new routes on a Linux machine in order to link it to your physical network.

Prerequisites

In order to add routes on your Linux machine, you need to have administrator rights.

In order to verify it, you can run the “sudo” command followed by the “-v” option (in order to update your cached credentials).

$ sudo -v

If you don’t have sudo rights, you can have a look at our dedicated articles on getting administrator rights on Ubuntu or CentOS.

Add route on Linux using ip

The easiest way to add a route on Linux is to use the “ip route add” command followed by the network address to be reached and the gateway to be used for this route.

$ ip route add <network_ip>/<cidr> via <gateway_ip>

# Example
$ ip route add 10.0.3.0/24 via 10.0.3.1

By default, if you don’t specify any network device, your first network card, your local loopback excluded, will be selected.

However, if you want to have a specific device, you can add it to the end of the command.

$ ip route add <network_ip>/<cidr> via <gateway_ip> dev <network_card_name>

As an example, let’s say that you want two LAN networks to be able to communicate with each other.

The network topology has three different Linux machines :

  • One Ubuntu computer that has the 10.0.2.2/24 IP address;
  • Another Ubuntu computer that has the 10.0.3.2/24 IP address;
  • One RHEL 8 computer that will act as a simple router for our two networks.

simple-lan-network

The first computer cannot ping the other computer, they are not in the same subnet : 10.0.2.0 for the first computer network and 10.0.3.0 for the second one network.
ping-unreachable

As the two hosts are not part of the same subnet, the ping command goes to the default gateway.

In order to see the routes already defined on your machine, use the “ip route” command with no arguments. You can also use the “ip r” command as an abbreviation.

$ ip r

ip-routes

This is the routing table of your Linux computer : every computer has one. A router happens to manage many more routes than that but it is essentially using the same routing syntax.

So how does one read that?

In order to understand this output, you have to read from top to bottom :

  • By default, network calls will be forwarded to the local default gateway which is 10.0.2.1
  • UNLESS your call is for the 10.0.2.0/24 network. In this case, it will simply be sent on your local network via your default physical link (physically a CAT network cable)
  • UNLESS your call is for the 169.254.0.0/16 network. In this case, it will also be sent on your local network using your default physical link.
Note : did you know? The 169.254.0.0/16 address is called APIPA (for Automatic IP Address Addressing). It is the default IP used by a system that failed to reach a DHCP server on the network.

In our case, in order to call the 10.0.3.2/24 IP address, the call will be forwarded to our 10.0.2.1 router.

However, is our router able to forward calls addressed to the 10.0.3.0/24 network?

A simple “ip r” command on the router can give us a hint.

ip-route-router

As you can see, the router is only linked to the 10.0.2.0/24 network which is obviously an issue.

In order to add a route on our Linux router, we use the “ip route add” command.

$ sudo ip route add 10.0.3.0/24 via 10.0.3.1

ip-route-add

Now, if you were to ping your second computer on the first computer, you would be able to reach it.

ping-first-computer

Awesome, you have successfully added a route from one Linux computer to another!

Adding permanent route configuration on Ubuntu

On Ubuntu, there are three ways of adding a permanent route to your Linux machine :

  • You can add it to your Network Manager configuration file;
  • You can edit your Netplan YAML configuration file;
  • You can add your route to the “/etc/network/interfaces” file if you are using an old Ubuntu distribution.

Using Network Manager

To add a permanent route to the Network Manager, you have to navigate to the connection file located at “/etc/NetworkManager/system-connections”.

listing-network-manager-connections

Edit your “Wired connection” file and add a “route1” property in the IPv4 part of the network configuration.

route1-property-network

The route has to be defined as : the network IP address followed by the CIDR, next the default gateway and finally the next-hop.

In order for the changes to be applied, you can restart your network connection, and execute the “route -n” command in order to see your route.

$ sudo nmcli connection reload

adding-route-network-manager

Awesome, you have added a permanent route to your Linux server!

Using Netplan

Netplan is an Ubuntu exclusive but it can be quite useful if you want to configure your network using a simple YAML file.

To add a permanent route using Netplan, add the following section to your “/etc/netplan” configuration file.

$ sudo vi /etc/netplan/<configuration_file>.yaml

netplan-configuration

For the changes to be applied, you will have to execute the “netplan” command with the “apply” argument.

$ sudo netplan apply

netplan-permanent-route

Congratulations, you have configured your network using Netplan. If you want to read more about Netplan and its objectives, you can have a look at the dedicated documentation.

Using /etc/network/interfaces

To add a permanent route to a distribution using ifup and ifdown, edit the “/etc/network/interfaces” file and add the following section.

$ sudo vi /etc/network/interfaces

auto eth0
iface eth0 inet static
      address 10.0.2.2
      netmask 255.255.255.0
      up route add -net 10.0.3.0 netmask 255.255.0.0 gw 10.0.2.1

Adding permanent route configuration on RHEL

By adding the route in the previous section, there is a chance that your distribution created a file for the route to be persisted.

However, if it is not the case, you need to add it in order to keep your route when restarting your server.

On RHEL and CentOS distributions, you need to create a file named “route-<device>” in the “/etc/sysconfig/network-scripts” folder.

$ sudo vi /etc/sysconfig/network-scripts/route-enp0s3

persistent-routes-linux

Add route on Linux using nmcli

Another way of adding a route on Linux is to use the “nmcli” utility and add an IPV4 route using the “modify” command.

$ sudo nmcli connection modify <interface_name> +ipv4.routes "<network_ip> <gateway_ip>"
Note : need a complete article about the Network Manager? We have a complete article about configuring your network using Network Manager.

For example, using the infrastructure of the previous section, in order to add a route, we would execute the following command.

$ sudo nmcli connection modify enp0s3 +ipv4.routes "10.0.3.0/24 10.0.3.1"

As changes are not made live, you will need to reload your network connections from disk using the “nmcli reload” command.

$ sudo nmcli connection reload

add-route-linux-nmcli-1

Awesome! Now there is a route between your first and second network.

As a consequence, you will be able to ping your second computer from the first computer.

ping-first-network

Adding a route using the network graphical interface

If you are not into executing commands in the terminal, luckily for you, there is a way to add a route on Linux using a graphical interface.

Whether you are on Ubuntu, Debian or RHEL makes no difference as they all share the same network panel on GNOME.

At the top right corner of your screen, look for a small network icon and click on it.

wired-connection-panel

Click on “Wired Connected” and look for the “Wired Settings” panel under it.

wired-settings-rhel

When the panel opens, look for the “Wired” section and click on the small gear wheel right next to it.

network-gear-wheel

In the “Wired” panel, you will be presented with many different parameters : your current IPv4 address, your current MAC address, an optional IPv6 address and your link speed.

local-network-parameters

In the “IPv4” tab, you will be presented with your current IP configured (most likely two for your computer to act as a Linux router).

Right under it, you will see the “Routes” section. In there, you can specify the input of the previous sections.

add-route-graphical-interface

When you are done, click on the “Apply” blue button at the top right corner of the window.

In order for the changes to be applied, you will need to restart your network. You can achieve that by clicking on the “on/off” toggle in the “Wired” window of the network parameters.

restart-network-linux

Done!

You have successfully added a route on Linux using the graphical interface, your computers should now be able to talk to each other.

Troubleshooting Internet issues on Linux

In some cases, you may want to add a route on your Linux because you want to be able to reach websites outside of your local network, say 8.8.8.8 for example.

As an example, let’s say that you have a local router linked to “Internet” that resides at 192.168.178.1/24.

Inspecting your current routes is an easy way for you to guess why you are not able to reach Internet websites.

The thought process is quite simple :

  • Is the IP that I am trying to reach a part of my subnet or not?
  • If yes, I should be able to reach it without any routes, everything will be handled by the ARP protocol and Ethernet.
  • If not, I need to have a route from my computer to a router that is able to forward requests to Internet.

However, remember that routes are two-lane highways : you need to be able to reach an external IP, but the external IP needs to be able to reach back to you.

As a consequence, routes need to be correctly defined on your local network architecture. As a diagram is more useful that a thousand words, here is a way to understand it.

troubleshoot-internet-issues

Whenever you are troubleshooting Internet issues, you have to think with routes : do I have a route from my computer to the computer that I am trying to reach?

Are the computers or routers between me and the target configured to handle my calls?

Reaching a part of the network is great, but is this part of the network able to answer me back?

In our diagram detailed above, our router may receive an answer from Google, but it has to know what to do with the request. In your local home network, you don’t have to worry about it as most of the requests are forwarded using the NAT protocol (short for Network Address Translation Protocol).

Conclusion

In this tutorial, you learnt how you can easily add a new route on many different Linux distributions.

Right now, as for other topics, some tools co-exist on Linux making the network configuration a bit convoluted sometimes.

However, we listed most of the options that you may encounter. If we forgot about an option, make sure to leave a comment for us to know.

If you are interested in Linux System Administration, make sure to have a look at our dedicated section on the website.

How To Zip Multiple Files on Linux

ZIP is by far one of the most popular archive file format among system administrators.

Used in order to save space on Linux filesystems, it can be used in order to zip multiple files on Linux easily.

In this tutorial, we are going to see how can easily zip multiple files on Linux using the zip command.

Prerequisites

In order to zip multiple files on Linux, you need to have zip installed.

If the zip command is not found on your system, make sure to install it using APT or YUM

$ sudo apt-get install zip

$ sudo yum install zip

Zip Multiple Files on Linux

In order to zip multiple files using the zip command, you can simply append all your filenames.

$ zip archive.zip file1 file2 file3

adding: file1 (stored 0%)
adding: file2 (stored 0%)
adding: file3 (stored 0%)

Alternatively, you can use a wildcard if you are able to group your files by extension.

$ zip archive.zip *.txt

adding: file.txt (stored 0%)
adding: license.txt (stored 0%)

$ zip archive.zip *.iso

adding: debian-10.iso (stored 0%)
adding: centos-8.iso (stored 0%)

Zip Multiple Directories on Linux

Similarly, you can zip multiple directories by simply appending the directory names to your command.

$ zip archive.zip directory1 directory2

adding: directory1/ (stored 0%)
adding: directory2/ (stored 0%)

Conclusion

In this tutorial, you learnt how you can easily zip multiple files on Linux using the zip command.

You also learnt that wildcards can be used and that you can zip multiple directories similarly.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to have a look.

How To Install AutoFS on Linux

Whether you are an experienced system administrator or just a regular user, you have probably already mounted drives on Linux.

Drives can be local to your machine or they can be accessed over the network by using the NFS protocol for example.

If you chose to mount drives permanently, you have probably added them to your fstab file.

Luckily for you, there is a better and more cost effective way of mounting drives : by using the AutoFS utility.

AutoFS is a utility that mount local or remote drives only when they are accessed : if you don’t use them, they will be unmounted automatically.

In this tutorial, you will learn how you can install and configure AutoFS on Linux systems.

Prerequisites

Before starting, it is important for you to have sudo privileges on your host.

To verify it, simply run the “sudo” command with the “-v” option : if you don’t see any options, you are good to go.

$ sudo -v

If you don’t have sudo privileges, you can follow this tutorial for Debian based hosts or this tutorial for CentOS based systems.

Installing AutoFS on Linux

Before installing the AutoFS utility, you need to make sure that your packages are up-to-date with repositories.

$ sudo apt-get update

Now that your system is updated, you can install AutoFS by running the “apt-get install” command with the “autofs” argument.

$ sudo apt-get install autofs

When installing the AutoFS package, the installation process will :

  • Create multiple configuration files in the /etc directory such as : auto.master, auto.net, auto.misc and so on;
  • Will create the AutoFS service in systemd;
  • Add the “automount” entry to your “nsswitch.conf” file and link it to the “files” source

Right after the installation, make sure that the AutoFS service is running with the “systemctl status” command

$ sudo systemctl status autofs

Installing AutoFS on Linux autofs-service

You can also enable the AutoFS service for it to be run at startup

$ sudo systemctl enable autofs

Now that AutoFS is correctly installed on your system, let’s see how you can start creating your first map.

How AutoFS works on Linux

Maps” are a key concept when it comes to AutoFS.

In AutoFS, you are mapping mount points with files (which is called an indirect map) or a mount point with a location or a device.

In its default configuration, AutoFS will start by reading maps defined in the autofs.master file in the /etc directory.

From there, it will start a thread for all the mount points defined in the map files defined in the master file.

How AutoFS works on Linux autofs

Starting a thread does not mean that the mount point is mounted when you first start AutoFS : it will only be mounted when it is accessed.

By default, after five minutes of inactivity, AutoFS will dismount (or unmount) mount points that are not used anymore.

Note : configuration parameters for AutoFS are available in the /etc/autofs.conf

Creating your first auto map file

Now that you have an idea on how AutoFS works, it is time for you to start creating your very first AutoFS map.

In the /etc directory, create a new map file named “auto.example“.

$ sudo touch /etc/auto.example

The goal of this map file will be to mount a NFS share located on one computer on the network.

The NFS share is located at the IP 192.168.178.29/24 on the local network and it exports one drive located at /var/share.

Before trying to automount the NFS share, it is a good practice to try mounting it manually as well as verifying that you can contact the remote server.

$ ping 192.168.178.29

Creating a direct map

The easiest mapping you can create using AutoFS is called a direct map or a direct mapping.

A direct map directly associates one mount point with a location (for example a NFS location)

Creating your first auto map file direct-mapping

As an example, let’s say that you want to mount a NFS share at boot time on the /tmp directory.

To create a direct map, edit your “auto.example” file and append the following content in it :

# Creating a direct map with AutoFS

# <mountpoint>    <options>    <remote_ip>:<location>   

/tmp              -fstype=nfs  192.168.178.29:/var/share

Now, you will need to add the direct map to your “auto.master” file.

To specify that you are referencing a direct map, you need to use the “-” notation

# Content of the auto.master file

/-    auto.example

direct-map

Now that your master file is modified, you can restart the AutoFS service for the changes to be effective.

$ sudo systemctl restart autofs

$ cd /tmp

Congratulations, you should now be able to access your files over NFS via direct mapping.

Creating a direct map tmp-nfs

Creating an indirect mapping

Now that you have discovered direct mappings, let’s see how you can use indirect mappings in order to mount remote location on your filesystem.

Indirect mappings use the same syntax as direct mappings with one small difference : instead of mounting locations directly to the mountpoint, you are mounting it in a location in this mountpoint.

Creating an indirect mapping

To understand it, create a file named “auto.nfs” and paste the following content in it

nfs    -fstype=nfs  192.168.178.29:/var/share

As you can see, the first column changed : in a direct map, you are using the path to the mountpoint (for example /tmp), but with an indirect map you are specifying the key.

The key will represent the directory name located in the mount point directory.

Edit your “auto.master” file and add the following content in it

/tmp   /etc/auto.nfs

Creating an indirect mapping autonfs

Restart your AutoFS service and head over to the “tmp” directory

$ sudo systemctl restart autofs

$ cd /tmp

By default, there won’t be anything displayed if you list the content of this directory : remember, AutoFS will only mount the directories when they are accessed.

In order for AutoFS to mount the directory, navigate to the directory named after the key that you specified in the “auto.nfs” file (called “nfs” in this case)

$ cd nfs

Awesome!

Your mountpoint is now active and you can start browsing your directory.

Mapping distant home directories

Now that you understand a bit more about direct and indirect mappings, you might ask yourself one question : what’s the point of having indirect mapping when you can simply map locations directly?

In order to be useful, indirect maps are meant to be used with wildcard characters.

One major use-case of the AutoFS utility is to be able to mount home directories remotely.

However, as usernames change from one user to another, you won’t be able to have a clean and nice-looking map file, you would have to map every user in a very redundant way.

# Without wildcards, you have very redundant map files

/home/antoine  <ip>:/home/antoine
/home/schkn    <ip>:/home/schkn
/home/devconnected <ip>:/home/devconnected

Luckily for you, there is a syntax that lets your dynamically create directories depending on what’s available on the server.

To illustrate this, create a new file named “auto.home” in your /etc directory and start editing it.

# Content of auto.home

*    <ip>:/home/&

In this case, there are two wilcards and it simply means that all the directories found in the /home directory on the server will be mapped to a directory of the same name on the client.

To illustrate this, let’s pretend that we have a NFS server running on the 192.168.178.29 IP address and that it contains all the home directories for our users.

# Content of auto.home

*   192.168.178.29:/home/&

Save your file and start editing your auto.master file in order to create your indirect mapping

$ sudo nano /etc/auto.master

# Content of auto.master

/home     /etc/auto.home

Save your master file and restart your AutoFS service for the changes to be applied.

$ sudo systemctl restart autofs

Now, you can head over to the /home directory and you should be able to see the directories correctly mounted for the users.

Note : if you see nothing in the directory, remember that you may need to access the directory one time for it to be mounted by AutoFS

Mapping distant home directories home-dir

Mapping and discovering hosts on your network

If you paid attention to the auto.master file, you probably noticed that there is an entry for the /net directory with a value “-hosts“.

The “-hosts” parameter is meant to represent all the entries defined in the /etc/hosts file.

As a reminder, the “hosts” file can be seen as a simple and local DNS resolver that associates a set of IPs with hostnames.

As an example, let’s define an entry for the NFS server into the /etc/hosts file by filling the IP and the hostname of the machine.

Mapping and discovering hosts on your network dns-resolver

First of all, make sure that some directories are exported on the server by running the “showmount” command on the client.

$ sudo showmount -e <server>

Mapping and discovering hosts on your network showmount

Now that you made sure that some directories are exported, head over to your “auto.master” file in /etc and add the following line.

# Content of auto.master

/net   -hosts

Save your file and restart your AutoFS service for the changes to be applied.

$ sudo systemctl restart autofs

That’s it!

Now your NFS share should be accessible in the /net directory under a directory named after your server hostname.

$ cd /net/<server_name>

$ cd /net/<server_ip>
Note : remember that you will need to directly navigate in the directory for it to be mounted. You won’t see it by simply listing the /net directory on the first mount.

Troubleshooting

In some cases, you may have some troubles while setting up AutoFS : when a device is busy or when you are not able to contact a remote host for example.

  • mount/umount : target is busy

As Linux is a multi-user system, you might have some users browsing some locations that you are trying to mount or unmount (using AutoFS or not)

If you want to know who is navigating the folder or who is using a file, you have to use the “lsof” command.

$ lsof +D <directory>
$ lsof <file>

Troubleshooting lsof

Note : the “+D” option is used in order to list who is using the resource recursively.
  • showmount is hanging when configuring host discovery

If you tried configuring host discovery by using the “-hosts” parameter, you might have verified that your remote hosts are accessible using the “showmount” command.

However, in some cases, the “showmount” command simply hangs as it is unable to contact the remote server.

Most of the time, the server firewall is blocking the requests made by the client.

If you have access to the server, you try to inspect the logs in order to see if the firewall (UFW for example) is blocking the requests or not.

firewall-blocking

  • Debugging using the automount utility

On recent distributions, the autofs utility is installed as a systemd service.

As a consequence, you can inspect the autofs logs by using the “journalctl” command.

$ sudo journalctl -u autofs.service

You can also use the “automount” utility in order to debug the auto mounts done by the service.

$ sudo systemctl stop autofs

$ sudo automount -f -v

Conclusion

In this tutorial, you learnt about the AutoFS utility : how it works and the differences between direct and indirect maps.

You also learnt that it can be configured in order to setup host discovery : out of the box, you can connect to all the NFS shares of your local network which is a very powerful tool.

Finally, you have seen how you can create indirect maps in order to automatically create home directories on the fly.

If you are interested in Linux system administration, we have a complete section dedicated to it, so make sure to have a look!

How To Check If File or Directory Exists in Bash

When working with Bash and shell scripting, you might need to check whether a directory or a file exists or not on your filesystem.

Based on this condition, you can exit the script or display a warning message for the end user for example.

In order to check whether a file or a directory exists with Bash, you are going to use “Bash tests”.

In this tutorial, you are going to learn how to check if a file or directory exists in a Bash script.

Check If File Exists

In order to check if a file exists in Bash, you have to use the “-f” option (for file) and specify the file that you want to check.

if [[ -f <file> ]]
then
    echo "<file> exists on your filesystem."
fi

For example, let’s say that you want to check if the file “/etc/passwd” exists on your filesystem or not.

In a script, you would write the following if statement.

#!/bin/bash

if [[ -f "/etc/passwd" ]]
then
    echo "This file exists on your filesystem."
fi

Check If File Exists check-file

Check File Existence using shorter forms

In some cases, you may be interested in checking if a file exists or not directly in your Bash shell.

In order to check if a file exists in Bash using shorter forms, specify the “-f” option in brackets and append the command that you want to run if it succeeds.

[[ -f <file> ]] && echo "This file exists!"

[ -f <file> ] && echo "This file exists!"

Using the example used before, if you want to check if the “/etc/passwd” file exists using shorter forms, you write the following command

[[ -f /etc/passwd ]] && echo "This file exists!"

Check File Existence using shorter forms check-file-shorter

So how does this command work?

Shorter forms are closely related to exit statuses.

When you run a command on Bash, it always exits with an error status : 0 for error and numbers greater than 0 for errors (1, 2.. 6 and so on)

In this case, the “&&” syntax will check if the exit status of the command on the left is equal to zero : if this is the case, it will execute the command on the right, otherwise it won’t execute it.

Protip : you can use “echo ${?}” in order to see the exit status of the latest command run

Checking multiple files

In some cases, you may want to check if multiple files exist on your filesystem or not.

In order to check if multiple files exist in Bash, use the “-f” flag and specify the files to be checked separated by the “&&” operator.

if [[ -f <file1> ]] && [[ -f <file2> ]]
then
  echo "They exist!"
fi

Check If File Does Not Exist

On the other hand, you may want to check if a file does not exist on your filesystem.

In order to check if a file does not exist using Bash, you have to use the “!” symbol followed by the “-f” option and the file that you want to check.

if [[ ! -f <file> ]]
then
    echo "<file> does not exist on your filesystem."
fi

Similarly, you can use shorter forms if you want to quickly check if a file does not exist directly in your terminal.

[[ ! -f <file> ]] && echo "This file does not exist!"

[ ! -f <file> ] && echo "This file does not exist!"

check-file-does-not-exist-shorter

Note that it is also possible to check if a file does not exist using the “||” operator.

The “||” operator will execute the command on the right if and only if the command on the left fails (i.e exits with a status greater than zero).

To test if a file does not exist using the “||” operator, simply check if it exists using the “-f” flag and specify the command to run if it fails.

[[ -f <file> ]] || echo "This file does not exist!"

Check If Directory Exists

In order to check if a directory exists in Bash, you have to use the “-d” option and specify the directory name to be checked.

if [[ -d "$DIRECTORY" ]]
then
    echo "$DIRECTORY exists on your filesystem."
fi

As an example, let’s say that you want to check with Bash if the directory /etc exists on your system.

In order to check its existence, you would write the following Bash script

#!/bin/bash

if [[ -d /etc ]]
then
    echo "/etc exists on your filesystem."
fi

When executing this script, you would get the following output

Output

$ /etc exists on your filesystem

Check Directory Existence using shorter forms

In some cases, you may be interested in checking if a directory exists or not directly in your Bash shell.

In order to check if a directory exists in Bash using shorter forms, specify the “-d” option in brackets and append the command that you want to run if it succeeds.

[[ -d <directory> ]] && echo "This directory exists!"

[ -d <directory> ] && echo "This directory exists!"

Let’s say that you want to check if the “/etc” directory exists for example.

Using the shorter syntax, you would write the following command.

[ -d /etc ] && echo "This directory exists!"

check-directory-2

Creating a complete Bash script

If you find yourself checking multiple times per day whether a file (or multiple) exists or not on your filesystem, it might be handy to have a script that can automate this task.

In this section, you are going to create a Bash script that can take multiple filenames and return if they exist or not.

If they don’t, a simple notification message will be displayed on the standard output.

Create a new Bash script and make it executable using chmod.

$ mkdir -p ~/bin 

$ cd ~/bin && touch check_file && chmod u+x check_file && vi check_file

Here is the content of the script to be used to dynamically check if files exist.

#!/bin/bash

# Using argument expansion to capture all files provided as arguments.

for FILE in ${@}
do
  if [[ ! -f $FILE ]]
  then
    echo "The file ${FILE} does not exist!"
  fi
done

Save your script and add the “bin” folder you just created to your PATH environment variable.

$ export PATH="~/bin:$PATH"

$ printenv PATH

~/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Now that your script is accessible wherever you are on the system, you can call your script and start checking if files exist or not.

$ check_file /etc/passwd /etc/pass /etc/file

The file /etc/pass does not exist!
The file /etc/file does not exist!

Awesome!

You created a custom to check whether files exist on your filesystem or not.

Conclusion

In this tutorial, you learnt how you can check if a file exists or not using Bash tests and Bash short syntax.

Similarly, you learnt how it is possible to verify if a directory exists.

Finally, you have written a complete Bash script that accepts dynamic arguments in order to check if multiple files exist or not.

If you are interested in Bash programming or in Linux System administration, we have a complete section dedicated to it on the website, so make sure to check it out!

Command Not Found in Bash Fixed

Every system administrator got this error at least one time in a shell : “bash : command not found“.

However, you were pretty sure that you wrote the command correctly, or that you installed the tool that you are actually trying to execute.

So why are you getting this error?

The “bash : command not found” error can happen for various reasons when running commands in a Bash terminal.

Today, we are taking a look at the different ways to solve the “command not found” error in Bash.

Bash & PATH concepts

Before starting out with the solution, it is important to have a few concepts about what the PATH environment variable is and how it is related to the commands you run.

PATH is an environment variable that lists the different directories that your bash terminal will visit in order to find utilities on your system.

To have a look at your PATH environment variable, simply use the “echo” command with the PATH variable.

$ echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

As you can see, PATH is defined by a list of different system paths delimited by colons.

They are the different paths visited by my interpreter in order to run commands.

If I were to remove an entry from the PATH, or remove the PATH all together, you would not be able to run commands in the bash without specifying the entire path to the binary.

It is an important point to understand because not being able to run a command does not mean that your binary was deleted on the system.

Now that you understand how environment variables are related to your bash interpreter, let’s see how you can solve your error.

Verify that the file exists on the system

The first step to solve this error is to verify that the command you are looking for actually exist on the system.

There are really no points going further if you mispelled the command or if you didn’t install it at all.

Let’s say for example that you cannot run the “ls” command.

Verify that the binary actually exists by searching for the binary on the system.

$ /usr/bin/find / -name ls 2> /dev/null

/bin/ls
/usr/lib/klibc/bin/ls

With the find command, you are able to locate the binary along with the directory where it is stored.

It is quite important because we will need to add this path to our PATH environment variable later on.

Verify your PATH environment variable

Most of the time, you will run into the “bash : command not found” after changing your PATH environment in order to add new entries.

First, verify that the path you searched for before is listed in your PATH environment variable.

$ echo $PATH

/home/user/custom:/home/user

As you can see here, the “/bin” directory is not listed in my PATH environment variable.

By default, the PATH is defined in the “/etc/environment” file for all the users on the system.

If your PATH environment variable is different from the one defined in the environment file, it is because you have overriden the PATH.

Now that you have two choices : either you know where you exported the PATH variable or you don’t.

Fixing your profile scripts : bashrc, bash_profile

In most of the cases, you modified the .bashrc or the .bash_profile file in order to add your PATH override.

To search where you exported your PATH, run the following command

$ /usr/bin/grep -rn --color "export PATH" ~/. 2> /dev/null

./.bashrc:121:export PATH="/home/devconnected"

This command returns the file where the PATH was exported as well as the line number.

Edit this file and add the path from the first section to the export statement.

$ nano /home/user/.bashrc

export PATH="/home/devconnected:/bin"

Save your file and exit the nano editor.

For the changes to be applied, you will have to source your current bash terminal.

This will ensure that the .bashrc file is executed again in the current shell terminal.

$ source .bashrc
Why can you execute source without having to specify the full path?

Because “source” is a shell built-in command.

Try executing “builtin source .bashrc” for example

Now, you can try to execute the command you failed to execute before.

$ ls

file  devconnected  file2  directory1  swap file3

Awesome!

You fixed the “bash : command not found” error on Linux!

Reset the PATH environment variable properly

Even if you solve your issue, you will have to define your PATH environment variable properly if you don’t want to modify your bashrc file all the time.

First, have a look at the PATH variable defined in the “/etc/environment” file.

$ cat /etc/environment

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

In order to reset your PATH environment variable on your environment, export the PATH defined in the environment file.

$ export=PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

Now, modify your .bashrc file but use the $PATH syntax in order to append your paths to the existing PATH variable.

$ sudo nano ~/.bashrc

export PATH="$PATH:/home/devconnected"

Exit the file and source your bashrc file for the changes to be applied.

$ source ~/.bashrc

$ echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/devconnected

Awesome!

You have successfully resetted your PATH environment variable, you should not get the “bash : command not found” error anymore.

Execute the command as sudo

In some cases, your PATH environment variable may be perfectly configured but you will have to execute the command as sudo.

You may get this error or just a simple “permission denied” error.

In any cases, first make sure that you have sudo rights with the sudo command.

$ sudo -l

User user may run the following commands on ubuntu:
    (ALL : ALL) ALL

If this is the case, you should be able to execute your command as sudo.

$ sudo <command>

Congratulations!

You have solved the “bash : command not found” error on your system.

Verify that the package is correctly installed

In some cases, you think that your command is installed but you didn’t install the command to begin with.

Let’s say for example that you are looking to run the “htop” command but you are not able to do it.

$ htop

bash : Command 'htop' not found

To verify if the command is correctly installed, depending on your distribution, run the following commands.

$ dkpg -s htop     [Ubuntu/Debian]

dpkg-query: package 'htop' is not installed and no information is available
Use dpkg --info (= dpkg-deb --info) to examine archive files,
and dpkg --contents (= dpkg-deb --contents) to list their contents.

$ rpm -qa | grep htop    [CentOS/RHEL]

In any case, you will have to install the command if you want to run it properly.

$ sudo apt-get install htop   [Ubuntu/Debian]

$ sudo yum install htop       [CentOS/RHEL]

Now you can try to run the command that was missing.

$ htop

Conclusion

In this tutorial, you learnt how you can solve the famous “bash : command not found” error that many system administrators encounter every day.

If you solve your issue with a solution that is not described in the article, make sure to leave a comment in order to help other administrators.

If you are interested in Linux system administration, we have a complete section dedicated to it on the website, so make sure to have a look.

How To Add and Delete Users on Debian 10 Buster

Adding and deleting users is one of the most basic tasks when starting from a fresh Debian 10 server.

Adding user can be quite useful. As your host grows, you want to add new users, assign them special permissions, like sudo rights for example.

In this tutorial, we are going all the ways to add and delete users on Debian 10 hosts.

Prerequisites

In order to add and delete users on Debian, you need to have sudo rights, or to belong to the sudo group.

If you are not sure about how to add a user to sudoers, make sure to check the tutorial we wrote about it.

To check your sudo rights, run the following command

$ sudo -v

If no error messages appear, you are good to go, otherwise ask your system administrator to provide you with sudo rights.

Adding a user using adduser

The first way to add users on Debian 10 is to use the adduser command.

The adduser command is very similar to the useradd command. However, it provides a more interactive way to add users on a Debian host.

Generally, it is preferred to use adduser rather than useradd (as recommended by the useradd man page itself)

To add a user, run this command

$ sudo adduser ricky

Adding user 'ricky'
Adding new group 'ricky' (1007)
Adding new user 'ricky' (1005) with group 'ricky'
Creating home directory '/home/ricky'
Copying files from '/etc/skel'

You will be asked to choose a password for the user

New password: <type your password>
Retype new password: <retype your password>
Changing the user information for ricky

Then you will be asked to specify some specific information about your new user.

You can leave some values blank if you want by pressing Enter.

Enter the new value, or press ENTER for the default
   Full Name []:
   Room Number []:
   Work Phone []:
   Home Phone []:
   Other []:

Finally, you will be asked if the information provided is correct. Simply press “Y” to add your new user.

Is the information correct? [Y/n] Y

Now that your user was created, you can add it to the sudo group.

Adding a user using useradd

$ sudo useradd <username>

To assign a password to the user, you can use the -p flag but it is not recommended as other users will be able to see the password.

To assign a password to a user, use the passwd command.

$ sudo passwd <username>

New password:
Retype new password:
passwd: password updated successfully

Add a user using the GNOME desktop

If you installed Debian 10 with GNOME, you can also create a user directly from the desktop environment.

In the Applications search bar, search for “Settings”.
Add a user using the GNOME desktop settingsIn the Settings window, find the “Details” option.

Add a user using the GNOME desktop

Click on “Details”, then click on “Users”.

Add a user using the GNOME desktop users

On the top right corner of the window, click on “Unlock”.

Add a user using the GNOME desktop unlock

Enter your password, and a “Add User” option should now appear in the panel.

Add a user using the GNOME desktop add-user

In the next window, choose what type of account you want for the user (either with sudo rights or not).

Fill the full name field, as well as the username field.

You can choose to assign a password now or you can let the user decide on its password on its next logon.

When you are done, simply click on “Add”.

gnome-add-user

Congratulations, your account was successfully created.

account

Check that your user was added

In order to check that your user was created on Linux, run the following command.

$ cat /etc/passwd | grep <user>
<user>:x:1005:1007:User,,,:/home/user:/bin/bash

If there are no entries for the user you just created, make sure to use the adduser command again.

Deleting a user using deluser

In order to delete a user on Debian 10, you have to use the deluser command.

$ sudo deluser <username>

To remove a user with its home directory, run the deluser command with the –remove-home parameter.

$ sudo deluser --remove-home <username>

Looking for files to backup/remove
Removing user 'user'
Warning: group 'user' has no more members.
Done.

To delete all the files associated with a user, use the –remove-all-files parameter.

$ sudo deluser --remove-all-files <username>

Deleting a sudo user with visudo

If you removed a sudo user on Debian, it is very likely that there is a remaining entry in your sudoers file.

To delete a user from the sudoers file, run visudo.

$ sudo visudo

Find the line corresponding to the user you just deleted, and remove this line.

<username>    ALL=(ALL:ALL) ALL

Save your file, and your user should not belong to the sudo group anymore.

Deleting a user using the GNOME Desktop

From the users panel we used to create a user before, find the “Remove user” option at the bottom of the window.
delete-account

Note : you need to unlock the panel to perform this operation.

When clicking on “Remove User”, you are asked if you want to keep the files owned by this user. In this case, I will choose to remove the files.

Deleting a user using the GNOME Desktop files

Troubleshooting

In some cases, you may have some error messages when trying to execute some of the commands above.

adduser : command not found on Debian

By default, the “adduser” command is located in the “/usr/sbin” folder of your system.

$ ls -l /usr/sbin/ | grep adduser
-rwxr-xr-x 1 root root    37322 Dec  5  2017 adduser

To solve this issue, you need to add “/usr/sbin” to your $PATH.

Edit your .bashrc file and add the following line

$ sudo nano ~/.bashrc

export PATH="$PATH:/usr/sbin/"

Source your bashrc file and try to run the adduser command again.

$ source ~/.bashrc

$ sudo adduser john
Adding user `john' ...
Adding new group `john' (1001) ...
Adding new user `john' (1001) with group `john' ...
Creating home directory `/home/john' ...
Copying files from `/etc/skel' ...

You solved the “adduser : command not found” problem on Debian 10.

Conclusion

As you can see, adding and deleting users on Debian 10 is pretty straightforward.

Now that your users are created, you can also set up SSH keys on Debian 10 for a seamless authentication.

How To Install and Enable SSH Server on Debian 10

This tutorial focuses on setting up and configuring a SSH server on a Debian 10 minimal server

SSH, for Secure Shell, is a network protocol that is used in order to operate remote logins to distant machines within a local network or over Internet. SSH architectures typically includes a SSH server that is used by SSH clients to connect to the remote machine.

As a system administrator, it is very likely that you are using SSH on a daily basis to connect to remote machines across your network.

As a consequence, when new hosts are onboarded to your infrastructure, you may have to configure them to install and enable SSH on them.

In this tutorial, we are going to see how you can install and enable SSH, via OpenSSH, on a Debian 10 distributions.

Prerequisites

In order to install a SSH server on Debian 10, you will need to have sudo privileges on your host.

To check whether you have sudo privileges or not, run the following command

$ sudo -l

If you are seeing the following entries on your terminal, it means that you have elevated privileges

sudo

By default, the ssh utility should be installed on your host, even on minimal configurations.

In order to check the version of your SSH utility, you can run the following command

$ ssh -V

ssh-utility

As you can see, I am running OpenSSH v7.9 with OpenSSL v1.1.1.

Note that it does not mean that SSH servers are installed on my host, it just means that I may able to connect to remote machines as a client using the SSH utility.

It also mean that specific utilities related the SSH protocol (such as scp for example) or related to FTP servers (such as sftp) will be available on my host.

Installing OpenSSH Server on Debian 10

First of all, make sure that your packages are up to date by running an update command

$ sudo apt-get update

Installing OpenSSH Server on Debian 10 apt-get-update

In order to install a SSH server on Debian 10, run the following command

$ sudo apt-get install openssh-server

The command should run a complete installation process and it should set up all the necessary files for your SSH server.

If the installation was successful, you should now have a sshd service installed on your host.

To check your newly installed service, run the following command

$ sudo systemctl status sshd

Installing OpenSSH Server on Debian 10 sshd-service
By default, your SSH server is going to run on port 22.

This is the default port assigned for SSH communications. You can check if this is the case on your host by running the following netstat command

$ netstat -tulpn | grep 22

netstat 2

Great! Your SSH server is now up and running on your Debian 10 host.

Enabling SSH traffic on your firewall settings

If you are using UFW as a default firewall on your Debian 10 system, it is likely that you need to allow SSH connections on your host.

To enable SSH connections on your host, run the following command

$ sudo ufw allow ssh

ufw-allow

Enable SSH server on system boot

As you probably saw, your SSH server is now running as a service on your host.

It is also very likely that it is instructed to start at boot time.

To check whether your service is enable or not, you can run the following command

$ sudo systemctl list-unit-files | grep enabled | grep ssh

If no results are shown on your terminal, enable the service and run the command again

$ sudo systemctl enable ssh

Enable SSH server on system boot service-enabled

Configuring your SSH server on Debian

Before giving access to users through SSH, it is important to have a set of secure settings to avoid being attacked, especially if your server is running as an online VPS.

As we already saw in the past, SSH attacks are pretty common but they can be avoided if we change default settings available.

By default, your SSH configuration files are located at /etc/ssh/

Configuring your SSH server on Debian ssh-config

In this directory, you are going to find many different configuration files, but the most important ones are :

  • ssh_config: defines SSH rules for clients. It means that it defines rules that are applied everytime you use SSH to connect to a remote host or to transfer files between hosts;
  • sshd_config: defines SSH rules for your SSH server. It is used for example to define the reachable SSH port or to deny specific users from communicating with your server.

We are obviously going to modify the server-wide part of our SSH setup as we are interested in configuring and securing our OpenSSH server.

Changing SSH default port

The first step towards running a secure SSH server is to change the default assigned by the OpenSSH server.

Edit your sshd_config configuration file and look for the following line.

#Port 22

Make sure to change your port to one that is not reserved for other protocols. I will choose 2222 in this case.

Changing SSH default port default-prot

When connecting to your host, if it not running on the default port, you are going to specify the SSH port yourself.

Please refer to the ‘Connecting to your SSH server’ section for further information.

Disabling Root Login on your SSH server

By default, root login is available on your SSH server.

It should obviously not be the case as it would be a complete disaster if hackers were to login as root on your server.

If by chance you disabled the root account in your Debian 10 installation, you can still configure your SSH server to refuse root login, in case you choose to re-enable your root login one day.

To disable root login on your SSH server, modify the following line

#PermitRootLogin

PermitRootLogin no

Disabling Root Login on your SSH server permitrootlogin

Configuring key-based SSH authentication

In SSH, there are two ways of connecting to your host : by using password authentication (what we are doing here), or having a set of SSH keys.

If you are curious about key-based SSH authentication on Debian 10, there is a tutorial available on the subject here.

Restarting your SSH server to apply changes

In order for the changes to be applied, restart your SSH service and make sure that it is correctly restarted

$ sudo systemctl restart sshd
$ sudo systemctl status sshd

Restarting your SSH server to apply changes status-ssh

Also, if you change the default port, make sure that the changes were correctly applied by running a simple netstat command

$ netstat -tulpn | grep 2222

Restarting your SSH server to apply changes 2222

Connecting to your SSH server

In order to connect to your SSH server, you are going to use the ssh command with the following syntax

$ ssh -p <port> <username>@<ip_address>

If you are connecting over a LAN network, make sure to get the local IP address of your machine with the following command

$ sudo ifconfig

Connecting to your SSH server ifconfig

For example, in order to connect to my own instance located at 127.0.0.1, I would run the following command

$ ssh -p 2222 <user>@127.0.0.1

You will be asked to provide your password and to certify that the authenticity of the server is correct.

Connecting to your SSH server ssh-localhost

Exiting your SSH server

In order to exit from your SSH server on Debian 10, you can hit Ctrl + D or type ‘logout’ and your connection will be terminated.

Exiting your SSH server logout-ssh

Disabling your SSH server

In order to disable your SSH server on Debian 10, run the following command

$ sudo systemctl stop sshd
$ sudo systemctl status sshd

Disabling your SSH server disable-ssh

From there, your SSH server won’t be accessible anymore.

Disabling your SSH server connection-refused

Troubleshooting

In some cases, you may run into many error messages when trying to setup a SSH server on Debian 10.

Here is the list of the common errors you might get during the setup.

Debian : SSH connection refused

Usually, you are getting this error because your firewall is not properly configured on Debian.

To solve “SSH connection refused” you have to double check your UFW firewall settings.

By default, Debian uses UFW as a default firewall, so you might want to check your firewall rules and see if SSH is correctly allowed.

$ sudo ufw status

Status: active
 
To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere

If you are using iptables, you can also have a check at your current IP rules with the iptables command.

$ sudo iptables -L -n

Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh

If the rule is not set for SSH, you can set by running the iptables command again.

$ sudo iptables -I INPUT -p tcp -m tcp --dport 22 -j ACCEPT

Debian : SSH access denied

Sometimes, you may be denied the access to your SSH server with this error message “SSH access denied” on Debian.

To solve this issue, it depends on the authentication method you are using.

SSH password access denied

If you are using the password method, double check your password and make sure you are entering it correctly.

Also, it is possible to configure SSH servers to allow only a specific subset of users : if this is the case, make sure you belong to that list.

Finally, if you want to log-in as root, make sure that you modified the “PermitRootLogin” option in your “sshd_config” file.

#PermitRootLogin

PermitRootLogin yes

SSH key access denied

If you are using SSH keys for your SSH authentication, you may need to double check that the key is correctly located in the “authorized_keys” file.

If you are not sure about how to do it, follow our guide about SSH key authentication on Debian 10.

Debian : Unable to locate package openssh-server

For this one, you have to make sure that you have set correctly your APT repositories.

Add the following entry to your sources.list file and update your packages.

$ sudo nano /etc/apt/sources.list

deb http://ftp.us.debian.org/debian wheezy main

$ sudo apt-get update

Conclusion

In this tutorial, you learnt how you can install and configure a SSH server on Debian 10 hosts.

You also learnt about basic configuration options that need to be applied in order to run a secure and robust SSH server over a LAN or over Internet.

If you are curious about Linux system administration, we have a ton of tutorials on the subject in a dedicated category.

How To Add Swap Space on Debian 10 Buster

This tutorial focuses on how to create swap space on Debian 10 via a swap file or a swap partition on your hard drive.

On a Linux system, it is very common to run out of memory, because you run too many programs, or because you run programs that are consuming too much memory.

As a consequence, if your RAM is full, you won’t be able to launch new programs on your computer.

You will have to manually shut down programs or tweak them to consume less memory.

There is however another way to virtually increase your memory : by using swap space.

In this tutorial, we are going to see how you can add swap space on Debian 10, either by creating a swap file or by creating a disk partition dedicated to swap.

Looking to add swap space on CentOS 8?

What is Swap Space on Debian?

Swap space is a space allocated to handle additional programs running when your RAM memory is full.

Let’s say that you have 4 GBs of RAM on your computer, and that 3 programs are already taking 3.5 GBs out of the 4 available.

What is Swap Space on Debian ram-1

If you are trying to run a program that is taking 1 GB on normal usage, you won’t be able to do it as you don’t have the space necessary for the program.

You could buy some RAM (which is expensive), or you could choose to create some swap space on your host.

When running your 1 GB program, your operating system (Linux here) will “move” or “swap” one of the programs to a dedicated part of your hard drive (your swap partition) and run your 1 GB program on the newly allocated space.

What is Swap Space on Debian ram-2

As you can imagine, the OS can switch programs from swap to RAM and vice versa.

The threshold to determine when programs should be switched from RAM to Swap is called the swappiness, but configuring ths swappiness will be reserved for another tutorial.

Now that you have some basics on what the swap space is and how the swap space works on Linux, let’s see on you can create some swap space on Debian 10.

Prerequisites

Sudo privileges

In order to add swap space on Debian 10 Buster, you need to have sudo privileges on your host.

Make sure this is the case by running the following command

$ sudo -v

If you are not getting any errors messages, you are good to go.

Checking existing swap partitions

In order to see existing swap partitions available on your host, run the following command

$ sudo swapon --show

If a partition is already existing, you should get at least one line as a result.

swap-show

As you can see, I already own a swap partition on my sda drive of size 8 GB.

As the current memory on my computer is sufficient, my host is not using swap at the moment.

If no swap spaces are configured on your system, this is the output that you should expect.

swap-show-2

Add Swap Space with a swap file

The first method to add swap space on Debian is to use a dedicated swap file.

Many tutorials are not specifying this detail, but swap files cannot contain any holes at all.

It means that you should not use the cp command to create your swap file.

It is also not recommended to use the fallocate commands on file systems that support preallocated files such as XFS and ext4.

As a consequence, you are going to use the dd command in order to add swap space on Debian.

add-swap-space-dd

In this case, we are going to create a 2 GB swap file.

Note : there are no performance improvements in using a swap file rather than creating a file partition. Swap files are just easier to manage because the file size can be easily adjusted. Changing the partition size for swap can be trickier than changing the file size.

a – Create a swapfile using dd

To add swap space, run the following command

$ sudo dd if=/dev/zero of=swapfile bs=1MiB count=$((2*2014))

Make sure that your swap file was created by issuing the following command.

$ ls -l swapfile

swap-2

b – Secure your swapfile with permissions

Swap files are only used by the operating system for memory optimization purposes.

As a consequence, it should not be modified by any users except for the root user.

Change the file permissions of your swapfile.

$ sudo chmod 600 /swapfile

c – Enable your swapfile

Now that your swapfile is secure, it is time to activate your swap space.

To enable swap space on Debian 10, run the following command.

$ sudo mkswap /swapfile

This is going to set the file as a swap file, setting the correct headers for the swapon binary.

mkswap

Now that the swapspace is correctly set, you can enable it.

$ sudo swapon /swapfile

To verify that your swap space is active, you can run the initial command with the –show flag.

$ sudo swapon --show

swapon-success

d – Make your swap space permanent

Similarly to the creation of filesystems, changes won’t be made permanent if you don’t append some changes to the fstab file.

If you leave it this way, your swap space will be erased at the next host reboot.

To make your swap space permanent, edit the /etc/fstab file and paste the following changes.

$ cd /etc/
$ sudo nano fstab

/swapfile none swap defaults 0 0

This configuration specifies that :

  • /swapfile: the name of the “swap filesystem” we are creating;
  • none: there is mount point for this filesystem
  • swap: the filesystem type used
  • defaults: the filesystem options, set as default for this example
  • 0: the dump option for the filesystem, as well as the pass option.

Save your file, and restart your changes to make sure that the changes are still effective.

$ sudo reboot
$ sudo swapon --show

Congratulations!

You successfully created swap space on Debian 10 using a swap file.

Add Swap Space with a swap partition

Another way to add swap space on Debian is to create a dedicated swap partition.

If you run the initial Debian 10 installation, there is a high chance that some swap partition is already created on your system.

However for this tutorial, we are going to start from scratch and create our own swap partition.

a – Create a swap space partition with fdisk

To have a look at the existing partitions on your host, run the following command

$ sudo fdisk -l

list-partition-1

As you can see, I already own a ext4 primary partition and a second partition that is not currently used.

We are going to add a swap partition as an extended or logical partition on sda.

Run the fdisk utility, and create a new partition on the hard drive that you want (sda in my case)

$ sudo fdisk /dev/sda

Welcome to fdisk (util-linux 2.30.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): n

Run the “n” command to add a new partition to your disk.

Note : if your host is running out of primary partitions, you can add swap space within an extended partition.
All space for primary partitions is in use
Adding logical partition 5
First sector (48291898-65062911, default 48291840):

You can leave the first sector option as default by just pressing Enter.

On the next prompt, specify the size of your swap partition. In this case, I am going to use 2 GiB again.

Last sector, +/-sectors or +/-size{K,M,G,T,P} : +2G

Created a new partition 5 of type 'Linux' and of size 2 GiB.

As you can see, partitions are created with the Linux partition type by default.

This is not what we want, since we want to have a swap partition on our drive.

To change the partition type, run the “t” command in fdisk.

Command (m for help): t
Partition number (1,2,5, default 5): 5
Hex code (type L to list all codes): 82

On Linux, swap partitions have the partition type ID 82 in fdisk.

Hit Enter, and make sure that your partition type was correctly changed.

Changed type of partition 'Linux' to 'Linux swap / Solaris'

Don’t forget to write your changes to disk as fdisk does not directly write to disk unless you ask it do it.

To write on disk, run the “w” command in fdisk.

The partition table has been altered
Syncing disks.

Make sure that your swap partition was correctly added by running the fdisk command again.

list-partition-2

Now that your swap partition is created, it is time to enable it on our Debian 10 host.

b – Enabling your swap partition

First, make sure to run the mkswap for the swap headers to be correctly set on your partition.

$ sudo mkswap /dev/sda5

mkswap-2
Now that your headers are set, run the swapon command.

$ sudo swapon /dev/sda5

Similarly to the other method, make sure that your swap space was correctly created.

$ sudo swapon --show

swapon-show-2

c – Make your swap space permanent

In order to make your swap space permanent, it needs to be added to the fstab file.

First of all, get the UUID for your newly created partition.

$ sudo blkid

c – Make your swap space permanent blkid

Copy the UUID value, and edit your fstab to append the following changes.

$ sudo nano /etc/fstab

UUID=4c46c5af-3530-486b-aabe-abca2543edca   none   swap  defaults   0   0

Save your file, and restart your system to make sure that your changes are permanent.

$ sudo reboot
$ sudo swapon --show

swapon-show-3

Congratulations, you correctly created a swap partition using fdisk on Debian 10 Buster.

Remove swap partition on Debian

Removing swap partitions on Debian is pretty straightforward : first you need to use the command “swapoff” on the swap partition you are trying to remove.

If you are not sure about your current existing partitions, run a simple “blkid” command.

$ blkid 

$ sudo swapon /dev/sda5

Finally, edit your fstab and remove the entry associated with the swap partition.

$ sudo nano fstab

UUID=4c46c5af-3530-486b-aabe-abca2543edca   none   swap  defaults   0   0     <--- To be removed.

Troubleshooting

When adding swap space on Debian 10 Buster, you may run into the following error.

Troubleshooting

swapon: /swapfile: read swap header failed.

This error is happening when you don’t run the mkswap command before running the swapon command.

As a reminder, mkswap sets the header for the file or the partition to be used as swap space.

If you forget to run the mkswap command, Linux won’t be able to assign it as swap space on your host.

Location of swap file on Linux

By default, swap files are located into the “/proc/swaps” directory of your system.

~$ cat /proc/swaps
Filename                Type        Size    Used    Priority
/swapfile               file        1025101 0       -1

From there, you know that your swap file is located at your root directory.

Another way to get the location of your swap file is to inspect the fstab file.

$ cat /etc/fstab

/swapfile    none     swap    sw     0       0

Conclusion

Today, you learnt that there are two ways to add swap space on a Debian 10 host, by creating a swap file or by creating a swap partition with fdisk.

How To Change User Password on Debian 10

On Debian 10, users are able to change their password pretty easily.

It is also possible, if you have sudo rights, to change user passwords as well as to define rules for password change on the host.

In this tutorial, we are going to see how you can change the user password on Debian 10 through the command-line and the user interface if you are using a GNOME desktop.

Change User Password using passwd

The first way to change the user password is to use the passwd command.

$ passwd

Changing password for devconnected.
Current password:
New password:
Retype new password:
passwd: password updated successfully

If you type the same password, you are going to have a warning message saying

Password unchanged

Change Another User’s Password with passwd

Before running the passwd command, make sure that you have sudo rights on your Debian 10 host.

To check sudo rights quickly, run the sudo command and make sure that you have error messages.

$ sudo -v

If you have sudo rights, you can run the passwd command.

Note: when updating another’s user account, you are not forced to know the current user password. It is very handy if you want to restrict the access to a user.

$ sudo passwd <user>

New password:
Retype new password:
passwd: password updated successfully

Delete Another User’s Password with passwd

Sometimes you want to reset the user password, maybe because it has lost it or because the password has been compromised.

You can set the password for the user, or you can delete the existing password to make the account passwordless.

To delete another user’s password, run the following command

$ sudo passwd -d <user>
passwd: password expiry information changed

Now when logging via the GNOME user interface, you won’t be prompted with a password. The account will automatically be logged in.

Note: deleting a user password must be done under rare circumstances and the account should be updated quickly to set a secure and long password.

User data might be compromised if no passwords are set for the account.

Expire Another User’s Password with passwd

When setting a passwd on Debian, the password will never expire by default.

But sometimes, because you want to apply correct password policies, you may want to set an expiration time or to expire some accounts after a given time.

To expire another user’s password on Debian, run the following command

$ sudo passwd --expire <user>
passwd: password expiry information changed

Now when logging on the other user account, it should be prompted to change its password.

Expire Another User’s Password with passwd expire-user-password

Change your password on the GNOME desktop

If you are using Debian 10 with a GNOME desktop, you can modify your password via the user interface.

System administrators tend to use the command line to perform administrative operations, but nothing forces you to do it this way.

1. In the Activities search box, type “Settings” and open it.

Add a user using the GNOME desktop settings

2. In the Settings window, choose the “Details” option.

Change your password on the GNOME desktop details-1

3. Choose the “Users” option, and find the user you want to modify.

Change your password on the GNOME desktop users-window

4. Click on the password field. Specify your old password and change your password to a secure one.

Change your password on the GNOME desktop change-password-debian

Click on “Change” and your password should be changed. Make sure to log again to test your new password.

Troubleshooting

In some cases, you may run into some errors while changing your password on Debian 10.

Here is the list of the most common errors and their solutions.

Default root password on Debian 10

By default, there is no default password for the root account on Debian 10.

This is because the root account is locked by default and setting a root password will unlock the account.

If you forgot your root password, you will have to reset it by rebooting and starting a bash shell into the GRUB.

Forgotten password on Debian 10

If you forgot your password on Debian, you will have to reset your password using the passwd command.

If you are not the system administrator, you have to ask the admin to run the passwd command in order to reset your password and make it expire immediately.

If you are the system administrator, you can run the passwd yourself.

$ sudo passwd <user>

If you remember the root password, connect as root and change the user password over there.

$ su -

$ passwd <user>

Conclusion

With this tutorial, you learnt how to change user password on Debian 10 Buster.

Another method to authenticate on a server is to use SSH keys. Make sure to check this article if you are interested in logging with SSH keys on Debian 10.

I hope that you learnt something new today.

Until then, have fun, as always.

Source Command on Linux Explained

The source command on Linux is a pretty popular function run by system administrators daily.

But what is the function of the source command?

Used to refresh the current shell environment, the source command can also be used in order to import functions into other bash scripts or to run scripts into the current shell environment.

In today’s tutorial, we are going to see how the source command should be used on Linux.

The commands will be executed in a Debian 10 environment with GNOME, but they will work for every distribution.

Source command internals

Before starting, it is important to have a complete understanding of what environment and shell variables are.

By default, on Linux, your system already owns a couple of environment variables to store various information such as the shell to use, your hostname or your current username.

Environment variables are initialized by the system and are inherited by all processes on the system. As a consequence, when you are running a shell instance, you are to get the value of environment variables on your system.

$ echo $USER
devconnected

On the other hand, shell variables are variables declared within the context of a shell instance and they are not shared with other shells or with child processes.

$ VARIABLE=devconnected
$ echo $VARIABLE
devconnected

On Linux, when you execute a script, it is most likely executed in a subshell.

As a consequence, you won’t be able to have the variables defined in your first shell running in the script, they simply don’t share the same environment.

This is what the source command solves.

The source command is used in order to evaluate the file passed as an argument in the context of the current execution. Shortened as ‘.’, the source command is mostly used in the context of shells run in terminal windows.

$ source filename [arguments]

Note that when arguments are provided, they are set as positional parameters for the script specified.

Note : the source documentation is located inside the bash documentation. To read it, type “man bash” and search for the source command paragraph.

Source command internals source-documentation

Source to update your current shell environment (.bashrc)

One of the main reasons to use source is to refresh the current shell environment by running the bashrc file.

As a reminder, .bashrc is a script file executed whenever you launch an interactive shell instance.

It is defined on a per-user basis and it is located in your home directory.

Let’s say for example that you want to add a new alias to your shell environment.

Open your .bashrc file and a new entry to it.

alias ll='ls -l'

Now try to run your new alias command directly in the terminal.

alias

As you can see, the changes were not directly applied in your current environment.

For the changes to be applied, run the source command with the .bashrc file as an argument.

$ source ~/.bashrc

An alternative way to do it is to run it with the dot syntax

$ . ~/.bashrc

If you try to execute your alias again, you should be able to run it

alias-working

Source to execute a script in the current context

As explained before, the source command can be used to execute a script in the context of the current environment.

To illustrate this point, let’s define a local shell variable in your current shell environment.

$ VARIABLE=devconnected

Now, create a new script and paste the following content in it

#!/bin/bash

echo $VARIABLE
echo $LOGNAME

The VARIABLE variable represents the local shell variable we created before and the LOGNAME variable is an environment variable on your host.

Save your script and give execute permissions to your newly created script (you will need sudo privileges to execute this command)

$ sudo chmod ugo+x <script>

If you try to execute the script, you should see the following result

logname-1

As you can see, the $VARIABLE local variable was not printed to the standard output.

This is because the script was executed in a subshell having its own set of local variables. The environment variable was printed however.

In order to execute this script in the context of our current shell, we are going to use the source command.

source-script

As you can see, in this case, the $VARIABLE variable was correctly printed to the standard output.

Source to import a script function

One of the great features of the source command is to update a script function, allowing a greater reusability of your existing shell functions.

To illustrate this point, let’s take the example of a function that prints the current user to the standard output.

Create a new script file and paste the following content inside.

$ nano script

#!/bin/bash
# Print the current user to the standard output
printUser() {
   echo $USER
}

Create another script and use the source function in order to import your printUser function.

$ nano import-script

#!/bin/bash
source ./script
printUser

Assign the correct permissions to the file you want to execute. You don’t need to have the execute permissions for the file containing the function you want to import.

$ sudo chmod u+x import-script
$ ./import-script

This is what you should see on your screen.

source-function

As you can see, the function was correctly imported and executed, printing the name of the current user of my host.

Source to read variables from a file

Another great usage of the source command on Linux is to read variables from a file.

Let’s say for example that you have a file with the following content in a file named “variables

NAME=devconnected
WEBSITE=devconnected.com
DESCRIPTION="best educational website online"

In another script file, you would be able to use those variables by using the source command to read variables.

Create a script and paste the following content in it.

$ nano variable-script

#!/bin/bash
source ./variables
echo $NAME is a website located at $WEBSITE and it is probably the $DESCRIPTION

source-variable

Troubleshooting

In some cases, you may run into errors when trying to source your files using the source command.

Here is a list of the common errors when trying to source files.

Source command not found on Linux

In some cases, you may run into this error

$ source: command not found

Or using sudo, you might also have a source command not found error.

$ sudo: source: command not found

The easy fix here is to execute the command as the root user by using “su”.

$ sudo -s
$ source .bashrc

Note that you can also use the “dot syntax” which is an equivalent to the source command.

$ . .bashrc

Conclusion

In today’s tutorial, you learnt what is the source command on Linux and how you can use to execute scripts in the context of the current environment.

You also learnt that it can be used to import functions or variables from a simple file to a script file.

If you want more tutorials related to Linux system administration, we have a complete category dedicated to it on devconnected. Click on the image below to read them.