Command Line Basics

The Linux command line is a text interface to your computer. Often referred to as the shell, terminal, console, prompt, or various other names, it can appear complex and confusing to use. Many users love claiming that the Linux command line is faster than a GUI. Command-line programs start faster than graphical ones because there’s less overhead. This is one reason distributions defaulted to the console environment when Linux first debuted on PCs. With this knowledge, let’s learn a bit more about the command line in Linux now.

Running the pwd command without options outputs the full path to the current working directory. For example, The command outputs the current working directory absolute path.

% pwd
/Users/vegibit

Make Directory – mkdir

The mkdir command in Linux allows users to create or make new directories. mkdir stands for “make directory.” With mkdir, you can also set permissions, create multiple directories (folders) at once, and much more.

% mkdir my_new_directory
% ls
my_new_directory

List Directory Contents – ls

The ls command is used to list files and directories. The contents of your current working directory, which is just a technical way of stating the directory that your terminal is presently in, will be listed if you run the ls command without further options.

% ls
blogpost.html regex.html uuid_finder.html vuetutorial.html

Change Directory – cd

The Linux cd command offers several ways to navigate and change the working directory using the terminal window. It lets you change directories using relative and absolute paths, move to parent or root directories, or find directories with incomplete names. Note: The cd command is a built-in shell command.

% cd node
node % pwd
/Users/node
node % cd ..
% pwd
/Users

Linux Filesystem Structure

The Linux filesystem unifies all physical hard drives and partitions into a single directory structure. It all starts at the top–the root (/) directory. All other directories and subdirectories are located under the single Linux root directory. A computer’s filesystem organizes the data stored so the user can easily retrieve it. Files are generally represented in a tree-like structure, in which any parent directory can have any number of children. The root directory is then found at the base of the tree.

Create New File – touch

The touch command comes as part of the GNU Core-utilities and creates a new file in Linux using the terminal. The touch command’s primary function is to modify a timestamp. Commonly, the utility is used for file creation, although this is not its primary function. The terminal program can change any file’s modification and access time. The touch command creates a file only if the file doesn’t already exist.

% touch new_file.py

The Command Line

The Linux command line is a text interface to your computer. Often referred to as the shell, terminal, console, prompt, or various other names, it can appear complex and confusing to use, but it is not that difficult. The command line usually begins with a % or $ character.

Clear The Terminal – clear

clear is a standard Unix computer operating system command used to clear the terminal screen. This command first looks for a terminal type in the environment, and after that, it figures out the terminal information database for how to clear the screen.

Autocomplete Typing – tab

Command-line completion (tab completion) is a common feature of command-line interpreters, in which the program automatically fills in partially typed commands. Use tab to autocomplete the names of directories and files while in the command line.

Up or Down Arrow

Linux maintains a history of commands you have entered. Using the up and down arrow keys, you can recall previously-entered commands to the command line, edit them and re-issue them. The up and down arrow commands at the Linux terminal are a fantastic way to speed up your workflow and save time.

Copy Files or Directories – cp

Use the cp command to create a copy of the contents of the file or directory specified by the SourceFile or SourceDirectory parameters into the file or directory specified by the TargetFile or TargetDirectory parameters. cp command requires at least two filenames in its arguments. Syntax: cp [OPTION] Source Destination cp [OPTION] Source Directory cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory First and second syntax is used to copy the Source file to the Destination file or Directory.

% cp new_file.py new_file_copy.py
% cp new_file.py backups         

Command Options

Administrators can use options to modify the behavior of shell commands. Shell command options are commonly represented by a single letter preceded by a -. For example, -l, -a, and -d could all be options that follow a shell command. Over time, a loose standard for the meanings of command-line option flags has evolved. The GNU utilities conform more closely to this “standard” than older UNIX utilities. Traditionally, UNIX command-line options consist of a dash followed by one or more lowercase letters. The GNU utilities added a double dash, followed by a complete word or compound word.

Move Files or Directores – mv

Use the mv command to move files and directories from one directory to another or to rename a file or directory. It retains its original name if you move a file or directory to a new folder without specifying a new name. The shell command mv is used to move a file into a directory. Use mv with the source file as the first argument and the destination directory as the second argument.

% mv index.php siteroot/

Remove Files and Directories – rm

Use the rm command to remove files you no longer need. The rm command removes the entries for a specified file, group of files, or specific select files from a list within a directory. User confirmation, read permission, and write permission are not required before a file is removed when you use the rm command. The shell command rm is used to delete files and directories. The -r flag deletes a directory and all its files and directories.

% rm -rf junk_folder

List Command Options

The shell command ls is used to list the contents in a directory. Linux administrators can combine it with the following command options:

ls -l Long Listing of Files in Linux

ls -a View Hidden Files in Linux

ls -lh List Files with Human Readable Format

ls -F List Files and Directories with ‘/’ Character at the End

ls -r List Files in Reverse Order in Linux

ls -R Recursively list Sub-Directories in Linux

ls -ltr List Files and Directories in Reverse Order in Linux

ls -lS Sort Files by File Size in Linux

ls -i Display Inode number of File or Directory

ls –help Show ls Command Help Page

ls -n Display UID and GID of Files

Append Redirection Operator

The >> shell command redirects the command’s standard output on the left and appends (adds) it to the end of the file on the right.

% echo 'Hi There!' >> hello.txt
% cat hello.txt
Hi There!
% echo 'Hello Again!' >> hello.txt
% cat hello.txt
Hi There!
Hello Again!

Pipe Operator

The | operator is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command’s output may act as input to the following command. It can also be visualized as a temporary connection between two or more commands, programs, or processes. The | operator is called a pipe. The pipe operator transfers the standard output from the command on its left into the standard input of the command on its right.

% cat hello.txt
Chris
John
Jim
Kevin
Sonya
Teresa
Alice
% cat hello.txt | sort
Alice
Chris
Jim
John
Kevin
Sonya
Teresa
% cat hello.txt | head -2
Chris
John

Redirecting Output

The > symbol redirects output by taking the output from the command on the left and passing it as input to the file on the right. We saw just above how to use the >> symbol to do something similar. This brings the question, what is the difference between >> and > in the Linux command line? The double >> symbol will append to any existing data, while the single > will overwrite existing data. This is a significant difference so keep that in mind when redirecting output in Linux!

% echo 'I overwrite all' > hello.txt
% cat hello.txt
I overwrite all

Display File Contents

The shell command cat displays the contents of one or more files to the terminal. This command is very frequently used in Linux. It reads data from the file and gives its content as output. It helps us to create, view, and concatenate files. We have seen several examples of using the cat command so far in this article.

Search with grep

The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern. The shell command grep searches files for lines that match a pattern and returns the results. Linux administrators can specify various options and the grep command to set the search.

Search for the given string in a single file

% grep "literal_string" filename.txt

Checking for the given string in multiple files.

% grep "some-string" example_*

Case insensitive search using grep -i

% grep -i "the" example_file

Match regular expressions in files

% grep "lines.*empty" example_file

Command Line Redirection

On a command line, redirection is the process of using the input and output of a file or command to use as input for another file. It is similar but different from pipes, allowing reading and writing from files instead of only commands.
As we saw in the section above, redirection can be done using the operators > and >>.

Command Line Environment

The command line’s environment refers to the current user’s settings and preferences. It enables users to set greetings, alias commands, variables, and more.

Shell Command env

The env command allows you to display your current environment or run a specified command in a changing environment. If no flags or parameters are set, the env command displays your current environment, showing one Name=Value pair per line. It is used to either print a list of environment variables or run another utility in an altered environment without having to modify the currently existing environment.

Shell Command alias

The shell command alias assigns commonly used commands to shortcuts (or aliases). You should wrap the given command in double quotes. The alias command instructs the shell to replace one string with another while executing the commands. When we often have to use a single significant command multiple times, in those cases, we create something called an alias for that command.

alias pd="pwd"
alias cls="clear"

Environment Variables

Linux environment variables are dynamic variables used by a shell and its child processes. Environment variables define various aspects related to how a Linux system works. For example, a user’s default shell is defined in the SHELL variable.

% printenv SHELL
/bin/zsh

Bash Profile

The Bash profile is a file on your computer that Bash runs every time a new Bash session is created. This is useful because we need to run specific codes every time before starting to work. OSX doesn’t include a Bash profile by default, but it lives in your home directory with the name if you already have one.

history command

The history command is used to view the previously executed command. This feature was not available in the Bourne shell. Bash and Korn support this feature in which every command executed is treated as the event and is associated with an event number using which they can be recalled and changed if required.

Export command

The export command makes a given variable available to all child sessions initiated from the current session. Export is a built-in command of the Bash shell. It marks variables and functions to be passed to child processes. Child processes will include a variable without affecting other environments.

% export USER="Linus"

HOME Environment Variable

$HOME is an environment variable present in command-line environments. It is used to get the path to the current user’s home directory. This makes it easy for programs to access the home directory when needed.

To show the path of the home directory, use the following command:

echo $HOME
/Users/vegibit

Command Line Summary

The default interface for Linux is the command line. The graphical interface is a suite of applications that run on Linux and are not necessary for Linux to function. The command line is often the fastest, most efficient way of getting work done. The advantages of the command line are as follows. The command line is high-speed. Many tasks are completed in the amount of time it takes to find the menu in a GUI. The command line is very efficient. A host requires less memory and CPU power if only running the command line instead of having a complete GUI. The command line is very powerful. In the case of CentOS, the graphical user interface can’t do many jobs easily from the GUI. The command line is more secure. By not installing a GUI, Linux has fewer applications and a much smaller attack vector for hackers. A more straightforward system is a more secure system. The command line isn’t always the best interface, though. It may be harder to remember how to complete jobs because it is very little in the way of visuals. With a GUI, you can browse the various menus and run programs to figure out how to use them. With a command line, this is near impossible. You need to study and understand the commands you can use. The command line is not very good for graphical tasks. Many tasks, such as browsing the web, watching videos, and editing photos, are better on the GUI. The key to getting the most out of our Linux system is to use the best tool for the job. For many jobs, this is the GUI, but for many others, the command line is better. There are several different ways of accessing the command line. The terminal emulator’s job is to emulate an older terminal that people used to use to access mainframe computers. A terminal was a keyboard and monitor connected to the mainframe via cables, allowing users to interact with the system. With the GNOME desktop, the default terminal emulator is called the GNOME terminal. Being an application means that one terminal emulator may have features that others don’t. These features may allow you to manage sessions or change the terminal’s appearance.

When you type in commands, a command interpreter takes these commands and interprets them so the kernel can carry out the instructions. This command interpreter is called a shell. The shell envelops the kernel. It provides a shell around the kernel. Whenever we want to send commands to the kernel, they need to be interpreted by the shell. All shells work similarly if you’re running commands on the hard drive. They execute the commands. However, different shells may offer command history, tab completion, command option completion, and more advanced shell scripting for automation. All of these features can help us be more efficient when we work. Popular shells are Bash, Dash, csh, ksh, and zsh.