One place for hosting & domains


      How to Reset a WordPress Admin Password Via the Command Line Using WP-CLI

      Part of the Series:
      Common WordPress Errors

      This tutorial series explains how to troubleshoot and fix common errors that you may encounter when deploying, maintaining, and updating your WordPress installation.

      Each tutorial in this series includes descriptions of common deployment, maintenance, or update errors, and explores ways to fix and optimize your installation to scale.


      In WordPress, oftentimes one of the most important pieces of information that is forgotten or misplaced is the admin password.

      In this tutorial, learn how to retrieve or reset your WordPress admin password from the command line using WP-CLI, a tool that allows users to manage WordPress blogs from a terminal.


      To follow this guide, you’ll need:

      • Access to a server as a regular system user with sudo privileges. You can follow one of our initial server setup guides to set this up.
      • A PHP environment running along a web server, with either Apache or Nginx. To set this up, you can follow either one of these tutorials:
      • A WordPress blog installed and secured. To set this up, you can follow either one of these tutorials, depending on which server you chose to use:
      • WP-CLI installed on your local machine or development server. To install WP-CLI, follow step 1 of our tutorial on “How To Manage Your WordPress Site From the Command Line”

      Step 1 — Resetting Your WordPress Admin Password via WP-CLI

      WP-CLI is a utility that allows you to perform administrative tasks via the command line. In this step, you’ll use the WP-CLI utility to reset your WordPress admin password.

      After you have successfully installed WP-CLI, navigate to your main WordPress directory:

      Next, you’ll grab a list of the users that are authorized to edit your WordPress site:


      Once the list is produced, locate the name and user ID of the admin user whose password you’d like to reset. To update the password for the user selected, enter the following, replacing the highlighted password with a secure password of your own choosing:

      • wp user update 1 --user_pass=password

      Your WordPress admin password should now be changed. In the next step, we’ll test the changes to ensure that your new admin password has been applied.

      Step 2 — Testing Your WordPress Admin Password

      After setting up a new admin password via WP-CLI, it’s a good idea to test the changes to be sure the password was applied correctly. To test your password, log in to the WordPress admin panel at, replacing the highlighted text with your website’s domain name or IP address.

      If you are able to log into your WordPress dashboard, you’ve successfully changed your WordPress admin password via WP-CLI. If you’ve encountered an error, repeat Step 1 using a new password, then attempt to log in again.


      In this tutorial, you used the WP-CLI utility to update your admin password. For more comprehensive information about WordPress, visit our list of WordPress resources.

      Source link

      How To Use WP-CLI v2 to Manage Your WordPress Site from the Command Line

      The author selected the Free Software Foundation to receive a donation as part of the Write for DOnations program.


      WP-CLI is a command-line tool for WordPress development and administrative tasks. It provides several commands that you can use to manage your WordPress website without needing to log in to the dashboard and navigate through the pages.

      Using WP-CLI to manage your WordPress installation over the conventional interface process helps to speed up your workflow. For many aspects of your website, you can also use WP-CLI in Bash scripts to automate tasks that are tedious or take a long time to perform.

      In this tutorial, you’ll use many of the features of WP-CLI and discover how it can fit into your workflow. You’ll cover common operations such as managing plugins and themes, creating content, working with the database, and updating WordPress. The capabilities of WP-CLI go beyond this tutorial; however, you’ll be able to transfer the skills from this tutorial to work with the more common options of other WP-CLI features.


      To follow this tutorial, you’ll need a secure WordPress installation. If you need to set up WordPress, you can follow these tutorials for your chosen server distribution:

      Note: It’s also possible to install WordPress with WP-CLI if you don’t have an existing setup, but we won’t be covering that aspect in this article.

      Step 1 — Installing WP-CLI

      In this step, you’ll install the latest version of the WP-CLI tool on your server. The tool is packaged in a Phar file, which is a packaging format for PHP applications that makes app deployment and distribution convenient.

      You can download the Phar file for WP-CLI through curl:

      • curl -O

      Once you have downloaded the file, run the following command to verify that it is working:

      You will receive the following output:


      OS: Linux 5.4.0-51-generic #56-Ubuntu SMP Mon Oct 5 14:28:49 UTC 2020 x86_64 Shell: /bin/bash PHP binary: /usr/bin/php7.4 PHP version: 7.4.3 php.ini used: /etc/php/7.4/cli/php.ini WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli WP-CLI vendor dir: phar://wp-cli.phar/vendor WP_CLI phar path: /home/ayo WP-CLI packages dir: WP-CLI global config: WP-CLI project config: WP-CLI version: 2.4.0

      Next, make the file executable with the following command:

      At this point, you can execute the wp-cli.phar file directly to access the WP-CLI tool. To make it available globally on the system, move it to your /usr/local/bin/ directory and rename it to wp. This ensures that you can access WP-CLI from any directory by entering the wp command at the start of a prompt:

      • sudo mv wp-cli.phar /usr/local/bin/wp

      Now, you will be able to issue the following command to check the installed version of WP-CLI:


      WP-CLI 2.4.0

      In this step, you installed WP-CLI on your server. You can check out alternative installation methods in the documentation. In subsequent sections, you’ll explore the tasks you can accomplish through the WP-CLI interface.

      Step 2 — Configuring WordPress Plugins

      It can be tedious to install and manage WordPress plugins through the admin user interface. It’s possible to offload such tasks to WP-CLI to make the process much faster. In this section you will learn to install, update, and delete plugins on a WordPress site through the command line.

      Before you proceed, make sure you are in the directory of your WordPress installation:

      Remember to change the highlighted directory name to the directory that contains your WordPress installation. This might be your domain name, if you followed the prerequisite tutorials.

      Listing Current Plugins

      You can list the currently installed plugins on a WordPress site with the following command:

      It displays a list of plugin names along with their status, version, and an indication of an available update.


      +---------+----------+-----------+---------+ | name | status | update | version | +---------+----------+-----------+---------+ | akismet | inactive | available | 4.1.7 | | hello | inactive | none | 1.7.2 | +---------+----------+-----------+---------+

      Searching for Plugins

      You can search for plugins through the search bar on the WordPress plugin repository page or you can use the following command for quicker access:

      Once you run this command, you will receive a list of the top 10 plugins that match the search term (as of early 2021). The expected output for the seo query is:


      Success: Showing 10 of 4278 plugins. +------------------------------------------------------------+---------------------+--------+ | name | slug | rating | +------------------------------------------------------------+---------------------+--------+ | Yoast SEO | wordpress-seo | 98 | | All in One SEO | all-in-one-seo-pack | 92 | | Rank Math – SEO Plugin for WordPress | seo-by-rank-math | 98 | | The SEO Framework | autodescription | 98 | | SEOPress, on-site SEO | wp-seopress | 98 | | Slim SEO – Fast & Automated WordPress SEO Plugin | slim-seo | 92 | | W3 Total Cache | w3-total-cache | 88 | | LiteSpeed Cache | litespeed-cache | 98 | | SEO 2021 by Squirrly (Smart Strategy) | squirrly-seo | 92 | | WP-Optimize – Clean, Compress, Cache. | wp-optimize | 96 | +------------------------------------------------------------+---------------------+--------+

      You can go to the next page by using the --page flag:

      • wp plugin search seo --page=2

      Take note of the value in the slug column. You’ll use this value to install or update the plugin on the command line.

      Installing Plugins

      You can install one or more plugins by using the wp plugin install command. You find the name of the plugin you want to install (in the slug column) and pass it as an argument to wp plugin install. You can also find the name of the plugin in the URL of the plugin page.

      Plugin name in URL

      • wp plugin install jetpack wordpress-seo gutenberg

      The output indicates the progress and completion of the installation of each of the plugins:


      Installing Jetpack – WP Security, Backup, Speed, & Growth (9.3.1) Downloading installation package from Unpacking the package... Installing the plugin... Plugin installed successfully. Installing Yoast SEO (15.6.2) Downloading installation package from Unpacking the package... Installing the plugin... Plugin installed successfully. Installing Gutenberg (9.8.1) Downloading installation package from Unpacking the package... Installing the plugin... Plugin installed successfully. Success: Installed 3 of 3 plugins.

      You can run the wp plugin list command again to confirm that you’ve installed the plugins successfully:


      +---------------+----------+-----------+---------+ | name | status | update | version | +---------------+----------+-----------+---------+ | akismet | inactive | available | 4.1.7 | | gutenberg | inactive | none | 9.8.1 | | hello | inactive | none | 1.7.2 | | jetpack | inactive | none | 9.3.1 | | wordpress-seo | inactive | none | 15.6.2 | +---------------+----------+-----------+---------+

      If you want to install a plugin from a remote source other than the WordPress plugin repository, you can pass the zip file’s URL as an argument to wp plugin install. This can be helpful for installing custom or premium plugins. For example, the following command will install the file hosted on Make sure to replace the highlighted URL with a link to the plugin zip file before running the command:

      • wp plugin install

      To install an older version of a plugin in the WordPress repository, specify the desired plugin version through the --version flag:

      • wp plugin install jetpack --version=8.0

      Activating and Deactivating Plugins

      You can install and activate plugins in one go by appending the --activate flag to wp plugin install:

      • wp plugin install redirection --activate


      Installing Redirection (5.0) Downloading installation package from Using cached file '/home/ayo/.wp-cli/cache/plugin/'... Unpacking the package... Installing the plugin... Plugin installed successfully. Activating 'redirection'... Warning: Plugin 'redirection' is already active. Success: Installed 1 of 1 plugins.

      To activate or deactivate one or more plugins, use the wp plugin activate and wp plugin deactivate commands respectively:

      • wp plugin activate jetpack gutenberg
      • wp plugin deactivate jetpack gutenberg

      Or you can use the --all flag to activate or deactivate all plugins at once. This is useful if you want to debug a problem in your WordPress installation:

      • wp plugin activate --all
      • wp plugin deactivate --all

      Updating Plugins

      You can update plugins through the wp plugin update command. You can choose to update a set of plugins or all of them at once by appending the --all flag. For example, to update the akismet plugin, you can run the following command:

      You would receive output similar to:


      Enabling Maintenance mode... Downloading update from Unpacking the update... Installing the latest version... Removing the old version of the plugin... Plugin updated successfully. Disabling Maintenance mode... +---------+-------------+-------------+---------+ | name | old_version | new_version | status | +---------+-------------+-------------+---------+ | akismet | 4.1.7 | 4.1.8 | Updated | +---------+-------------+-------------+---------+ Success: Updated 1 of 1 plugins.

      Deleting plugins

      To delete WordPress plugins, you can use the wp plugin delete command. You can specify one or more plugins to delete like the following:

      • wp plugin delete redirection

      Your output will confirm the deletion:


      Deleted 'redirection' plugin. Success: Deleted 1 of 1 plugins.

      You can also delete all the installed plugins in one go by appending the --all flag instead of specifying the plugin names one after the other:

      In this step, you’ve used WP-CLI to manage the plugins on your WordPress website. It’s much faster to perform actions compared to clicking through the admin dashboard. In the next section, you’ll leverage WP-CLI for installing and managing WordPress themes.

      Step 3 — Configuring Themes

      The process of managing themes through WP-CLI is almost identical to the way you can use it to manage plugins. In this section, you’ll source and apply new themes to a WordPress website through the wp theme subcommand.

      First, check what themes you currently have installed on the website:

      You’ll receive a list of the installed themes:


      +-----------------+----------+-----------+---------+ | name | status | update | version | +-----------------+----------+-----------+---------+ | twentynineteen | inactive | available | 1.8 | | twentytwenty | inactive | none | 1.6 | | twentytwentyone | active | available | 1.0 | +-----------------+----------+-----------+---------+

      There are three themes currently installed and the active one is twentytwentyone. If you want to find something with more features, you can try a search like the following:

      The output shows there are 832 themes that match the color search term:


      Success: Showing 10 of 832 themes. +---------------------+---------------------+--------+ | name | slug | rating | +---------------------+---------------------+--------+ | Color | color | 0 | | All Colors | all-colors | 100 | | Color Blog | color-blog | 98 | | Color Block | color-block | 0 | | X Blog color | x-blog-color | 0 | | Multicolor Business | multicolor-business | 0 | | ColorNews | colornews | 100 | | Colorist | colorist | 100 | | ColorMag | colormag | 98 | | MultiColors | multicolors | 74 | +---------------------+---------------------+--------+

      You can page through the results using the --page flag. For this example, just go ahead and install the ColorMag theme since it has a pretty good rating. The --activate flag activates the theme immediately:

      • wp theme install colormag --activate

      The output will confirm the installation:


      Installing ColorMag (2.0.4) Downloading installation package from Unpacking the package... Installing the theme... Theme installed successfully. Activating 'colormag'... Success: Switched to 'ColorMag' theme. Success: Installed 1 of 1 themes.

      If you visit your website, you’ll find that the ColorMag theme was applied successfully.

      ColorMag theme

      The output from the wp theme list command notes that there is an update available for both the twentynineteen and twentytwentyone themes. You can update them both using the following command:

      You’ll receive output similar to the following:


      Downloading update from Unpacking the update... Installing the latest version... Removing the old version of the theme... Theme updated successfully. Downloading update from Unpacking the update... Installing the latest version... Removing the old version of the theme... Theme updated successfully. +-----------------+-------------+-------------+---------+ | name | old_version | new_version | status | +-----------------+-------------+-------------+---------+ | twentynineteen | 1.8 | 1.9 | Updated | | twentytwentyone | 1.0 | 1.1 | Updated | +-----------------+-------------+-------------+---------+ Success: Updated 2 of 2 themes.

      The wp theme command offers many subcommands that can help you achieve tasks like getting the details of a theme, checking if a particular theme is installed, or even deleting one or more themes. You can explore all of the options by prepending help before the subcommand, as in wp help theme or wp help theme install.

      Now that you can manage themes through WP-CLI, you’ll review the options that the tool provides for managing WordPress content.

      Step 4 — Creating Posts and Pages

      WP-CLI provides several ways to manage content through the command line. It can be more comfortable to write posts in the terminal if you’re familiar with a command-line editor like nano or vim.

      You can browse the list of posts on the site with:

      You’ll receive a list of posts:


      +----+--------------+-------------+---------------------+-------------+ | ID | post_title | post_name | post_date | post_status | +----+--------------+-------------+---------------------+-------------+ | 1 | Hello world! | hello-world | 2021-01-24 12:32:06 | publish | +----+--------------+-------------+---------------------+-------------+

      The output shows one published post with the title of Hello world! and an ID of 1. To delete this post, use the wp post delete command and pass it the post ID:

      Your output will confirm the post’s deletion:


      Success: Trashed post 1.

      To create a new post, run the following command:

      • wp post create --post_status=publish --post_title="Sample post created with WP-CLI" --edit

      This command uses the --post_status flag to set the status of the post. Setting it to publish ensures that the post is published immediately after running the command. If you want to create a draft instead, set the --post_status flag to draft. The --post_title flag is how you can specify the title of the post, while --edit causes the post body to be opened in the default system editor (vim). You can find out the other flags that you can use in conjunction with the create subcommand by typing wp help post create in your terminal.

      Once the vim editor is open, press the i key to enter INSERT mode then enter the content of the post into the editor. Once you’re done editing the post, exit the vim editor by pressing the ESC button then type :wq and press ENTER. You will receive the following output after exiting vim:


      Success: Created post 6.

      If you enter the wp post list command again, you will find the post you just created. You can also check the frontend of the website.

      WP-CLI post

      Instead of writing the post on the command line, it’s also possible to import the post content from a text file. First, you need to create the file. For example:

      Next, open the file in a command-line editor to add or edit your content:

      Once you’re through with the edits, save and close the file by pressing CTRL-X followed by Y to save. You can import the contents of that file as a WordPress post by using the following command. All you need to do is specify the path to the file after the create subcommand. For the example file here, you would run:

      • wp post create ./content.txt --post_title="Sample Post Created with WP-CLI" --post_status=publish

      If you want to create a page instead of a post, append the --post_type flag and set it to page:

      • wp post create --post_title="A simple page" --post_status=draft --post_type=page

      Generating Posts or Pages

      WP-CLI also provides an option to cleanly generate posts and pages with dummy data. This is useful if you need custom data to quickly test a theme or plugin that you are developing. The following command is to generate posts. If you don’t include additional flags, it will generate 100 posts by default.

      You can change the number of posts generated by using the --count flag:

      • wp post generate --count=20

      If you want to generate pages instead of posts, append the --post_type flag and set it to page:

      • wp post generate --count=20 --post_type=page

      You can also use the wp help post generate to see other available options that can help you get your desired result.

      WordPress Revisions

      It is not uncommon for older sites to have tens or hundreds of revisions on their main pages due to years of editing and updating content. Revisions can be helpful in case you need to revert back to a previous version of your content, but they can also hurt the performance if there are too many. You can clean up all the post revisions in the WordPress database by executing the following command:

      • wp post delete $(wp post list --post_type="revision" --format=ids) --force

      The command enclosed in the parenthesis is evaluated first and it will produce the ids of all the post revisions that are present passing them to the delete subcommand. The --force flag is necessary because posts of type 'revision' do not support being sent to trash.

      Step 5 — Managing Your Database

      One of the most useful features of WP-CLI is its ability to interact with the MySQL database. For example, if you need an interactive session, you can enter a MySQL prompt with the following command:

      You can then use the MySQL shell as you normally would and, once you are through with your tasks, exit the shell by typing exit.

      For one-off queries, you can use the wp db query command by passing a valid SQL query as an argument to the command. For example, to list all the registered users in the WordPress database, you could run:

      • wp db query "SELECT user_login,ID FROM wp_users;"

      You will be presented with an output similar to the following:


      +------------+----+ | user_login | ID | +------------+----+ | admin | 1 | +------------+----+

      With wp db query you can run any one-off SQL query for the WordPress database.

      Backing Up and Restoring

      WP-CLI also allows you to back up your WordPress database. Running this following command will place a SQL dump file in the current directory. This file contains your entire WordPress database including your posts, pages, user accounts, menus, and so on:

      Once the file is produced, you can move it to a different location for safekeeping:


      Success: Exported to 'wordpress-2021-01-25-25618e7.sql'.

      You can also import a SQL dump file into your database through the wp db import command. This is useful when you are migrating a WordPress website from one location to another.

      Searching and Replacing

      Another common operation you can perform with WP-CLI is a find-and-replace operation. You can make a dry run first to find out how many instances it would modify. The first string is the search component while the second is the replacement:

      • wp search-replace --dry-run '' ''

      After running this, your output would be similar to the following:


      Success: 10 replacements to be made.

      Once you are sure you want to proceed, remove the --dry-run flag from the previous command:

      • wp search-replace '' ''

      In this step, you’ve reviewed several database operations that you can perform using WP-CLI. You can also complete other operations, such as optimizing the database, viewing database tables, deleting a database, or resetting one. You can explore the other options under the wp db subcommand by typing wp help db in your terminal.

      Step 6 — Updating WordPress

      You can update the core WordPress file with WP-CLI. You can examine the current version of WordPress that you have installed by running:



      You can check for updates through the wp core check-update command. If your version is not the latest, this will produce an output similar to the following:


      +---------+-------------+-----------------------------------------------------------------------+ | version | update_type | package_url | +---------+-------------+-----------------------------------------------------------------------+ | 5.6.1 | minor | | +---------+-------------+-----------------------------------------------------------------------+

      If an update is available, you can install it with:


      Updating to version 5.6.1 (en_US)... PHP Warning: Declaration of WP_CLICoreCoreUpgrader::download_package($package, $check_signatures = true) should be compatible with WP_Upgrader::download_package($package, $check_signatures = false, $hook_extra = Array) in phar:///usr/local/bin/wp/vendor/wp-cli/core-command/src/WP_CLI/Core/CoreUpgrader.php on line 30 Warning: Declaration of WP_CLICoreCoreUpgrader::download_package($package, $check_signatures = true) should be compatible with WP_Upgrader::download_package($package, $check_signatures = false, $hook_extra = Array) in phar:///usr/local/bin/wp/vendor/wp-cli/core-command/src/WP_CLI/Core/CoreUpgrader.php on line 30 Downloading update from Unpacking the update... Success: WordPress updated successfully.

      You can also update to a specific version by setting the --version flag to the version number. If you want to revert to an older version, you also need to add the --force flag, but this isn’t recommended:

      • wp core update --version=5.6
      • wp core update --version=5.0 --force

      In this final step, you updated your version of WordPress with WP-CLI.


      For WordPress developers and adminstrator’s working on the command line, WP-CLI is a great addition to the toolbox. In this tutorial, we covered several of the more common tasks that you can perform through the command line.

      WP-CLI has many more commands and options that you can familiarize yourself with to achieve even more on the command line without the web interface. Use wp help <command> to find out all the things you can do with a specific subcommand. There are also many community tools that extend WP-CLI with even more features.

      For more tutorials on WordPress, check out our WordPress topic page.

      Source link

      A Linux Command Line Primer


      Today, many of us are familiar with computers (desktops and laptops), smartphones, and tablets which have graphical user interfaces (also referred to as GUIs), allowing us to navigate apps, the web, and our files (like documents and photos) through a visual experience. The Windows, macOS, and Linux operating systems each present varieties of a desktop environment (with images of folders and files, for example), and dropdown menus, all of which provide access to computer programs, applications, and our own media.

      Although GUIs can be an intuitive way to use a computer for many users, they often do not provide us with the greatest power over our machines, and they may prevent us from having full administrative access on our machines, including installing, modifying, or deleting software or files. Additionally, as GUIs are largely visual, they are often not as accessible as they could be for all users.

      One way of navigating both your own personal computer and remote cloud servers without a GUI is through a text-based terminal or command-line interface (CLI). You can launch one in the browser by clicking on the blue Launch an Interactive Terminal! button, below:

      Launch an Interactive Terminal!

      Terminal interfaces exist on almost every computer operating system, and terminal emulators are also available as apps for tablets and smartphones. Terminals provide users with greater overall access to their machines through increased administrator access, greater ability to customize environments, and opportunities to automate processes. They also provide users with the ability to access remote computers, such as cloud servers.

      This tutorial will provide users who are new to terminal environments with the basics of using a command-line interface through an embedded web terminal in your browser, which you can launch below. If you already have some familiarity with terminals, you may prefer to go through our Introduction to the Linux Terminal tutorial instead. Once you complete this tutorial, you should have an understanding of how to use a terminal on a Linux (or macOS) computer or server.

      Understanding the Terminal Window

      When you first get access to a new computer or smartphone, you likely want to turn it on and get a feel for how to use it by checking which apps are available, and to learn where things are so that you can customize the device to suit your needs. You can become familiar with a computer through a terminal in a similar way.

      The interactive terminal you launched in this browser window, by clicking the Launch an Interactive Terminal! button above, displays a black rectangle on the bottom of your browser window:

      Screenshot of the Katacoda Terminal Environment

      If you have not launched the terminal, please do so now:

      Launch an Interactive Terminal!

      In your interactive browser terminal, there should be a dollar sign, $ and a blinking cursor. This is where you will begin to type commands to tell the terminal what to do.

      The terminal you have launched is an Ubuntu 20.04 terminal. Ubuntu is a popular distribution of Linux, which was originally based on the Unix operating system. The macOS operating system is also based on Unix. If you are reading this tutorial on a Linux or macOS machine, you should have a terminal on your operating system that works similarly to the embedded terminal we’ll be using in this guide.

      In many of these Unix (or *nix-based) operating systems, the symbols at the end of the prompt may be a $ symbol or a # symbol, which mean the following:

      • $ or dollar sign — you are logged in as a regular user
      • # or hashtag/pound symbol — you are logged in as a user with elevated privileges

      The user that is noted in the # environment is also known as a root user, which is considered to be a super user, or administrator, by default.

      For our purposes within the browser terminal below, you are logged in as a regular user, but you also have administrator privileges. As this is a temporary terminal, you do not need to worry about what you type into the terminal, as we will destroy everything once we are done. Similarly, with a cloud server, it is possible to destroy a server and start fresh if something goes awry.

      Please note that it is best to exercise more care when working on a local computer’s terminal as there may be changes you can make as an administrator on the terminal that can make permanent changes on the computer you are using.

      At this point, with your terminal launched in the browser, you can begin to type into it using your local computer. Your text will appear at the blinking cursor. We’ll learn about what we can type here in the next sections.

      Becoming Familiar with Directories

      We’ll begin working with the terminal by typing a command. A command is an instruction that is given by a user, communicating what it is that the user wants the computer to do. You will be typing your commands into the terminal and then pressing ENTER or RETURN when you are ready for the computer to execute on a given command.

      Let’s type the following command followed by ENTER. You can also copy the command, or ask it to run in a launched interactive terminal by clicking on the relevant links in the code block below when you hover over it with a mouse.

      Once you run this command, you’ll receive the following output:



      The pwd command stands for “present working directory,” and it lets you know where you are within the current filesystem.

      In this example, you are in the directory (or folder) called /root, which stands for the user called root, a user with elevated privileges. On a personal computer, this directory may be called the name of the user who owns the computer. Sammy Shark’s computer may have /sammy or /sammy-shark as their primary user directory.

      Right now, this directory is empty. Let’s create a directory to store the files we’ll be creating as we go through this tutorial, which we can call files, for example.

      To do this, we’ll use the mkdir command, which stands for “make directory.” After we type the command, we’ll need to write the name of the folder, which will pass the value to the command so that the command can execute on creating this directory. This value (the name of the folder) is known as an argument, which is an input being given to the command. If you are familiar with natural language grammar, you can think of the argument as an object that is being acted upon by the verb of the command.

      In order to create a new directory called files we’ll write the following, with mkdir being the command and files being the argument:

      After you run this command, you won’t receive any output other than a new line with a blinking cursor. With this fresh line on your terminal, you are ready for your next command.

      Listing Contents and Understanding Permissions

      As we have not received any concrete feedback about our new directory yet, we’ll use a command to learn more about what is in our present working directory. You can confirm that the new directory is indeed there by listing out the files in the directory, with the ls command (signifying “list”):

      You’ll receive output that confirms the files directory is there:



      This gives us general information about what is in our present working directory. If we want to have more details, we can run the ls command with what is called a flag. In Linux commands, a flag is written with a hyphen - and letters, passing additional options (and more arguments) to the command. In our example, we’ll add the -l flag, which — when paired with ls — denotes that we would like to use the option to use a long listing format with our command.

      Let’s type this command and flag, like so:

      Upon pressing ENTER, we’ll receive the following output in our terminal:


      total 4 drwxr-xr-x 2 root root 4096 Nov 13 18:06 files

      Here, there are two lines of output. The first line refers to computer memory blocks being allocated to this directory, the second line mostly refers to user permissions on the file.

      To get a somewhat more human readable output, we can also pass the -h or --human-readable flag, which will print memory sizes in a human readable format, as below. Generally, one hyphen - refers to single-letter options, and two hyphens -- refer to options that are written out in words. Note that some options can use both formats. We can build multiple options into a command by chaining flags together, as in -lh.

      For example, the two commands below deliver the same results even though they are written differently:

      Both of these commands will return the following output, similar to the output above but with greater context of the memory blocks:


      total 4.0K drwxr-xr-x 2 root root 4.0K Nov 13 18:06 files

      The first line of output lets us know that 4K of computer memory is dedicated to the folder. The second line of output has many more details, which we’ll go over in more detail. A general high-level reference of all the information that we’ll cover is indicated in the table below.

      File type Permissions Link count Owner Group File size Last modified date File name
      d rwxr-xr-x 2 root root 4.0K Nov 13 18:06 files

      You’ll note that the name of our directory, files, is at the end of the second line of output. This name indicates which specific item in the /root user directory is being described by the line of output. If we had another file in the directory, we would have another line of output with details on that file.

      At the front of the line, there is a list of characters and dashes. Let’s break down the meaning of each of the characters:

      Character Description
      d directory (or folder) — a type of file that can hold other files, useful for organizing a file system; if this were - instead, this would refer to a non-directory file
      r read — permission to open and read a file, or list the contents of a directory
      w write — permission to modify the content of a file; and to add, remove, rename files in a directory
      x execute — permission to run a file that is a program, or to enter and access files within a directory

      In the first drwx characters of the string, the first letter d means that the item files is a directory. If this were a file other than a directory, this string of characters would begin with a hyphen instead, as in -rwx, where the first hyphen signifies a non-directory file. The following three letters, rwx, represent the permissions for the owner of the directory files, and mean that the directory files can be read, written, and executed by the owner of the file. If any of these characters were replaced with hyphens, that would mean that the owner does not have the type of permission represented by that character. We’ll discuss how to identify the owner of a file in just a moment.

      The next three characters in the output are r-x, which represent the group permissions for the files directory. In this instance, the group has read and execute permissions, but not write permissions, as the w is replaced with a -. We’ll discuss how to identify the group in just a moment.

      The final three characters of the first string, r-x represents the permissions for any other groups that have access to the machine. In this case, these user groups can also read and execute, but not write.

      The number 2 in the output refers to the number of links to this file. In Linux, links provide a method to create shortcuts to help users navigate the filesystem. When you created this file, Linux did some background work to create an absolute link to the file, and a self-referential link to the file to allow for users to navigate along a relative path. We’ll discuss absolute and relative paths in the next section.

      After the number 2, the word root is displayed twice. This part of the output gives information about the owner and group associated with the files directory. The first instance of root in this line refers to the owner of the directory, whose permissions we saw earlier are rwx. The root user is the owner as we created the files directory as the root user and are the current owner of the file. Though the root user is the only user in our current environment, Unix-like operating systems often have more than one user and so it is useful to know which user has ownership of a file.

      The second instance of root refers to the group that has access to the files directory, whose permissions we saw earlier are r-x. In this case, the group name is the same as the owner username root. In real-world environments, there may be other groups on the operating system that have access to the directory, such as staff or a username like sammy.

      The rest of the details on this output line are the 4.0K for the memory allocation of the directory on the machine, and the date that the directory was last modified (so far, we have just created it).

      With this greater understanding of file systems and permissions, we can move onto navigating the file system on our Linux terminal.

      So far, we have learned how to determine where we are in a filesystem, how to make a new directory, how to list out files, and how to determine permissions.

      Let’s next learn how to move around the file system. We have made a new directory, but we are still in the main /root user directory. In order to move into the /files directory that we have created, we’ll use the cd command and pass the name of the directory we want to move into as the argument. The command cd stands for “change directory,” and we’ll construct it like so:

      Again, you won’t receive output other than a new line with a blinking cursor, but we can check that we are in the /files directory with the pwd command we used earlier:

      You’ll get the following output, confirming where you are:



      This validates that you are in the /files directory of the /root user directory. Does this syntax look familiar to you? It may remind you of a website’s URL with its forward slashes, and, indeed, websites are structured on servers within directories, too.

      Let’s move to the primary directory of the server. Regardless of where we are in a filesystem, we can always use the command cd / to move to the primary directory:

      To confirm that we have moved and learn what is in this directory, let’s run our list command:

      We’ll receive the following output:


      bin boot dev etc home lib lib32 lib64 libx32 media mnt opt proc root run s sbin srv sys tmp usr var

      There are a lot of files in there! The / directory is the main directory of a Linux server, referred to as the “root” directory. Note that the root directory is different from the default “root” user. You can think of the / directory as the major artery of a Linux machine, as it contains all the folders necessary to run the computer. For example, the sys directory holds the Linux kernel and system information virtual filesystem. If you would like to learn more about each of these directories, you can visit the Linux Foundation documentation.

      You’ll also notice that there is a directory we have been in already, the /root user folder. From the / directory, we can change directories back into /root then back into /files, or we can move directly back into that folder by typing the absolute path there with cd:

      Now, if you run pwd you’ll receive /root/files as your output.

      A file path is the representation of where a file or directory is located on your computer or server. You can call a path to a file or directory in either a relative or absolute way. A relative path would be when we move to a location relative to our current working directory, like we did when we were already in root/ and then moved into files/. An absolute path is when we call the direct line to a location, as we did above with /root/files, showing that we started in the / directory, called the root/ user directory and then the nested files/ directory.

      Additionally, Linux leveragesdot notation to help users navigate via relative paths. A single . stands for the directory you are currently in, and a double .. stands for the parent directory. So, from where we currently are (/root/files), we can use two dots to return to the parent root/ user directory, like so:

      If you run pwd, you’ll receive /root as your output, and if you run ls, you’ll receive files as your output.

      Another important symbol to be familiar with is ~ which stands for the home directory of your machine. Here, our home directory is called root/ for the root user, but on a local machine it may be your own name as in sammy-shark/.

      You can type the following from anywhere on your machine and return to this home directory:

      At this point, feel free to navigate around your file system with the commands you have learned so far. In the next section, we’ll begin working with text files.

      Creating and Modifying Text Files

      Now that we have a foundation in the Linux file system and how to get around it, let’s start creating new files and learn about how to manipulate text on the command line.

      Let’s first be sure that we’re in the files/ directory of the root/ user folder, which we can do by either verifying with pwd, or by changing directories on the absolute path:

      Now, we’ll create a new text file. We’ll be making a .txt file, which is a standard file that can be read across operating systems. Unlike .doc files, a .txt file is composed of unformatted text. Unformatted text, including the text in.txt files, can readily be used on the command line, and therefore can be used when working with textual data programmatically (as in, to automate text analysis, to pull information from text, and more).

      We’ll begin by using the touch command, which can create a new file or modify an existing file. To use it, you can use the command touch and pass the name of the text file you want to create as the argument, as demonstrated below.

      Once you press ENTER, you’ll receive a new line of the command prompt, and you can list the current contents of files/ to ensure it was created.



      So far we have created an ocean.txt file which contains no text at the time of creation.

      If we want to create a text file that is initialized with text, we can use the echo command, which is used to display strings of text in Linux.

      We can use echo directly on the command line to have the interface repeat after us. The traditional first program, "Hello, World!", can be written with echo like so:


      Hello, World!

      Named for Echo of Ovid’s Metamorphosis, the echo command returns back what we request. In this case, it echoed, “Hello, World!” On its own, however, the echo command does not allow us to store the value of our text into a text file. In order to do that, we will need to type the following:

      • echo "Sammy the Shark" > sammy.txt

      The above command uses echo, then the text we would like to add to our file in quotes, then the redirection operator >, and finally the name of our new text file, sammy.txt.

      We can check that our new file exists, again with ls.


      ocean.txt sammy.txt

      We now have two text files in our root/ user folder. Next, we can confirm that the file sammy.txt does have the text we asked the terminal to echo into it. We can do that with the cat command. Short for concatenate, the cat command is very useful for working with files. Among its functions is showing the contents of a file.

      Once we run the command, we’ll receive the following output:


      Sammy the Shark

      If we were to run cat on the empty file ocean.txt, we would receive nothing in return as there is no text in that file. We can add text to this existing file with echo as well. Let’s add a quote from Zora Neale Hurston to the file.

      • echo "Some people could look at a mud puddle and see an ocean with ships." > ocean.txt

      Now, if we run cat on the file, we’ll receive output of the text we just entered.


      Some people could look at a mud puddle and see an ocean with ships.

      So far, we have created text files and have added text to these files, but we have not yet modified these files. If we would like to do that, we can use a command-line text editor. Several popular choices exist, including Vim and Emacs. For our purposes, we’ll use nano, which is a less complex CLI text editor program that we can use to begin our exploration.

      The nano text editor can be summoned with the nano command. If we want to edit our existing sammy.txt file, we can do so by passing the file name as an argument.

      The file will open up on your terminal:


      Sammy the Shark

      With your keyboard’s arrow keys, move your cursor to the end of the line and begin typing a few lines from the perspective of Sammy.

      Note: On the command line, you can’t use your mouse or other pointer to navigate, both through the file system and within files. You’ll need to use your keyboard, and your arrow keys in particular, to move around textual files.

      When you’re done with your file, it may read something like this:


      Sammy the Shark
      Hello, I am Sammy.
      I am studying computer science.
      Nice to meet you!

      With your file now containing the text you would like, we can now save and close the file. You may notice that there is some guidance at the bottom of your terminal window:

      ^G Get Help   ^O WriteOut   ^R Read File  ^Y Prev Page  ^K Cut Text   ^C Cur Pos
      ^X Exit       ^J Justify    ^W Where Is   ^V Next Page  ^U UnCut Text ^T To Spell

      Because we are currently done with working on this file, we would like to Exit the file. Here, the ^ symbol refers to the Control or CTRL key on your keyboard, and the output above tells us that we need to combine that key with X (use this lower case, without pressing the SHIFT key) in order to leave the file. Let’s press those two keys together:

      CTRL x

      The above is often written inline as CTRL + X or Ctrl+x in technical documentation.

      At this point, you’ll receive the following prompt:


      Save modified buffer? Y Yes N No ^C Cancel

      In order to save it, we’ll press the letter y for yes:


      You’ll receive feedback like the following.


      File Name to Write: sammy.txt

      There are additional options, including cancelling with CTRL + C, but if you are comfortable with closing the file, you can press ENTER at this point to save the file and exit it.

      Let’s say that we want to make a few files of students at DigitalOcean University. Let’s create a new directory in files/ called students:

      Next, let’s move sammy.txt into the new students/ directory. The mv command, which stands for move, will allow us to change the location of a file. The command is constructed by taking the file we want to move as the first argument, and the new location as the second argument. Both of the following executions will produce the same result.

      • mv sammy.txt students/sammy.txt

      This latter option would be useful if we would like to change the name of the file, as in mv sammy.txt students/sammy-the-shark.txt.

      Now, if we run the ls command, we’ll see that only ocean.txt and the students/ directory are in our current directory (files/). Let’s move into the students/ folder.

      In order to have a template for the other students, we can copy the sammy.txt file to create more files. To do this, we can use the cp command, which stands for copy. This command works similarly to the mv command, taking the original file as the first argument, and the new file as the second argument. We’ll make a file for Alex the Leafy Seadragon:

      Now, we can open alex.txt and inspect it.

      So far, alex.txt looks identical to sammy.txt. By replacing some of the words, we can modify this file to read like the following. Note that you can use CTRL + K to remove an entire line.


      Alex the Leafy Seadragon
      Hello, I am Alex.
      I am studying oceanography.
      Nice to meet you!

      You can save and close the file by pressing CTRL + X then y then ENTER.

      If you would like to get more practice with text files, consider creating files for Jamie the Mantis Shrimp, Jesse the Octopus, Drew the Squid, or Taylor the Yellowfin Tuna.

      Once you feel comfortable with creating, editing, copying, and moving text files, we can move onto the next section.

      Autocompletion and History

      Many versions of the command line, including the interactive terminal embedded in this tutorial, allow you to autocomplete and to reuse commands as you go. This supports you moving more quickly as it saves you typing time.

      Try typing cat along with the first few letters of one of the text files you have been working on — for example, cat sa. Before you finish typing the whole file name of sammy.txt, press the TAB key instead. This should autocomplete the full file name, so that your terminal prompt displays the following:

      Now, if you press ENTER, the terminal should return the contents of the file to the command line.

      Another shortcut is to press the UP arrow key, which will let you cycle through the most recent commands you have run. On a new line with a blinking cursor, press the UP arrow key a few times to have quick access to your previous commands.

      If you need to replicate all the commands you have done in your terminal, you can also summon the entire history of this session with the aptly named history command:

      Depending on how much you have practiced, you should receive 30 or more lines of commands, starting with the following output:


      1 pwd 2 mkdir files 3 ls 4 ls -l ...

      Familiarizing yourself with these shortcuts will support you as you become more proficient with the command line interface.

      Working with Files from the Web

      One of the most exciting aspects of working on a command line interface connected to the internet is that you have access to all of the resources on the web, and can act on them in an automated way. With the terminal, you can also directly access cloud servers that you have credentials for, manage and orchestrate cloud infrastructure, build your own web apps, and more. For now, as we have already learned how to work with text files on the terminal, we’ll go over how to pull down a text file from the web so that the machine we are using has that text file available to us.

      Let’s move back into the files/ directory:

      From here, we’ll use the curl command to transfer data from the web to our personal interactive terminal on the browser. The command curl stands for client URL (web address).

      We have uploaded a short passage from Jules Verne’s Twenty Thousand Leagues Under the Seas on a cloud server. We’ll pass the URL of that file to the curl command, as demonstrated below.

      • curl

      Once we press ENTER, we’ll receive the text of the passage as output to our terminal (excerpted below)


      "You like the sea, Captain?" "Yes; I love it! The sea is everything. It covers seven tenths of the terrestrial globe. ... "Captain Nemo," said I to my host, who had just thrown himself on one of the divans, "this is a library which would do honor to more than one of the continental palaces, and I am absolutely astounded when I consider that it can follow you to the bottom of the seas."

      While it’s interesting to have the text display on our terminal window, we do not have the file available to us, we have only transferred the data but have not stored it. (You can verify that the file is not there by running ls).

      In order to save the text to a file, we’ll need to run curl with the -O flag, which enables us to output the text to a file, taking the same name of the remote file for our local copy.

      • curl -O

      You’ll receive feedback from the terminal that your file has downloaded.


      % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 2671 100 2671 0 0 68487 0 --:--:-- --:--:-- --:--:-- 68487

      If you would like to use a specific and alternate name of the file, you could do so with the -o flag and pass the name of the new file as an argument (in this case, jules.txt).

      • curl -o jules.txt

      We can now work on this file exactly as we would any other text file. Try using cat, or editing it with nano.

      In the next section, we’ll clean up some of the files and exit our terminal.

      Removing Files and Terminating Commands

      As with any other computer, we sometimes need to remove files and folders that are no longer relevant, and exit the program we are using.

      Let’s say that the students we know from DigitalOcean University have graduated and we need to clean up their files and the relevant folder. Ensure you are in the students/ directory:

      If you run ls, your folder may have a few files, like so:


      alex.txt drew.txt jamie.txt jesse.txt sammy.txt taylor.txt

      We can remove individual files with the rm command, which stands for remove. We’ll need to pass the file we want to remove as the argument.

      Warning: Note that once you remove a file, it cannot be undone. Be sure that you want to remove the file before pressing ENTER.

      Now, if we run ls, we’ll notice that sammy.txt is no longer in the folder:


      alex.txt drew.txt jamie.txt jesse.txt taylor.txt

      While we now know we can remove individual files with rm, it is not very time efficient if we want to remove the entire students/ directory and all of its contents.

      The command that is used to remove directories is called rmdir, which stands for remove directory. Let’s move to the parent folder of files so that we can work with the students/ directory from there (we would not be able to delete a folder we are presently in).

      From the root/ user directory, we can run rmdir on students.

      However, this does not work, as we receive the following feedback:


      rmdir: failed to remove 'students': Directory not empty

      The command did not work as rmdir only works on empty directories and the students directory still has files in it. (Here, you can create a new, empty folder, and try rmdir on it. Empty folders can be removed with rmdir.)

      To remove the directory with files still inside, we’ll need to try a different option. In computer science, recursion is commonly used to iteratively self-reference; so we can call both a primary item and all its dependencies. Using the rm command, we can recursively remove the primary students directory and all of its content dependencies. We’ll use the -r flag, which stands for recursive, and pass the folder students as the argument.

      At this point, if we run ls, we’ll notice that students/ is no longer in our present directory, and none of the files it held are available either, as they have all been deleted.

      When you are done with a terminal session, and especially when you are working on a remote server, you can exit the terminal with the exit command. Once you feel comfortable with what you have achieved in this session (as you won’t be able to restore it), you can type the following, followed by ENTER to leave the terminal.

      On our interactive terminal, we’ll receive the following output, confirming that our session has ended.


      The environment has expired. Please refresh to get a new environment.

      With this session complete, you can refresh this page and then launch a new terminal to try out alternate commands, or create a new file system to explore.


      Congratulations! You now know your way around the terminal interface, and are well on your way to doing more with computers and servers.

      Source link