Command Line Tips and Tricks

Posted on December 21, 2016 by fasihxkhatib

Introduction

The command line is a powerful tool at the disposal of every Linux user. Although Linux distros come with beautiful user interfaces, it is worthwhile to learn the command line. The command line allows you to do a number of things that you otherwise cannot do from the GUI, like write scripts to automate tasks for example.This guide covers the most common commands used in Linux, and also provides nifty tips and tricks.

Requirements

To follow this guide, you’ll need access to a Linux or Mac machine. You’ll need some familiarity with using the terminal to execute commands. If you aren’t familiar with using the terminal, feel free to take advantage of the resources available at Linux Academy to get up to speed. Also, if you’d like access to a Linux machine, you can use Linux Academy’s cloud servers. Other resources are listed at the end of this guide.

Moving around the file system

This section covers commands that help you with everyday filesystem tasks like creating, deleting, renaming, and moving files and directories, changing the permission and owner, etc.

View current directory

me@home:~$ pwd/home/me

Change directory

me@home:~$ cd /opt

You can use tilde (~) to refer to your home directory, a dot (.) to refer to the current directory, and two dots (..) to refer to the parent directory.Paths written after cd may be absolute paths or relative paths. An absolute path specifies the complete path from the root directory. For example, /home/john is an absolute path.

In contrast, a relative path begins with the current directory you are in. Suppose you are in the home directory, you can refer to the downloads directory as ./Downloads where . specifies the current directory. Simply typing cd will take you to the home directory.

Create a directory

me@home:~$ mkdir dir

List contents of a directory

me@home:~$ ls dir

ls lists the content of the directory. To see the permissions associated with the contents of the directory, use the -l flag. To view hidden files and directories, use the -a flag.

Simply typing ls will show you the contents of the current directory.

Change permissions

me@home:~$ chmod 777 file1

The example here grants read, write, and execute permissions to the owner, group, and others.chmodcommand is used to change the permissions associated with files and directories. For a more detailed explanation on how to change permissions, please refer to our guide on managing permissions.

Change owner

me@home:~$ chown john /opt/file1me@home:~$ chown john:john /opt/file1

chown is used to change the owner of a file or directory. The first example shows how to change the owner of a file. However, changing the owner this way leaves the group associated with the file unchanged. To change both the user and the group, use the second form where you specify user:group.

Move files

me@home:~$ mv file1 dir/

mv is used to move files and directories. The example shown moves file1 into the directory dir. If a directory were to be moved from one location to another, all of the subdirectories would also be moved to the new location.

Rename files

me@home:~$ mv file1 file2

Here the mv command renames file1 to file2.

Copying files

me@home:~$ cp file1 file2 me@home:~$ cp -r dir1 dir2

cp is used to copy the contents of files and directories. The first example shown copies the contents of file1 into file2. The second example copies the contents of dir1 into dir2. The -r flag specifies that the directory should be copied recursively.

Removing files

me@home:~$ rm file1 me@home:~$ rm -rf dir1

rm is used to remove files or directories. The first example shows how to remove a file. The second example shows how to remove a directory. A directory can only be removed if it is empty. If it has subdirectories with files in them, you’d have to delete those first. The -r flag is used to recursively delete the subdirectories. The -f flag is used to force remove the content of the directory. Without this flag, you’ll be prompted before each piece of content is removed.

Locating files

me@home:~$ locate -i .bashrc

locate is used to find files by name. The -i flag is used to ignore case when locating files. locate works by searching for the string you enter in the database created by updatedb command.

There is also the find command which searches the filesystem in real time and also allows you to search for files based on attributes.

Searching content within files

me@home:~$ grep -i root /etc/passwd root:x:0:0:root:/root:/bin/bash

grep is used to find files that contain the term or pattern you are looking for. In the example shown, we’re searching for the term “root” in /etc/passwd. The lines that contain the term are printed in the standard output. The -i flag is used to make the search case insensitive.

Managing processes

Being a multitasking operating system means there’s multiple processes running simultaneously. This section covers commands that you’ll use to manage processes.

View processes

ps is used to list the running processes. If you’d like more information to be displayed, use the -u flag. The second example uses the aux flags to list all the processes and pipes it through to less so that you can scroll through the output.

ps provides a snapshot of the running processes. If you’d like to view processes in real time, use the top command. By default, the list of processes will be sorted by the percentage of CPU usage in descending order. However, you can change the sorting criteria. In addition, with top, you can also change how much CPU a process gets or kill the process altogether.

Start background process

me@home:~$ vim &[1] 6449

Adding an ampersand (&) at the end of the command moves it into the background. Since this is the first command we’ve sent to the background, it’s given the number 1. 6449 is the process ID.

View background processes

me@home:~$ jobs [1]+ Stopped vim

jobs is used to view background jobs. The + sign shows that this is the most recently added command to the background.

Bring process to foreground

me@home:~$ fg %1

fg is used to bring processes to the foreground. %1 brings the first job to the foreground.

Kill process

kill is used to kill a process. To kill a process you need to specify a signal, here SIGKILL, and the process ID of the process to kill.

Similar to kill is killall that lets you kill processes by name instead of process ID. The downside, however, is that you may end up killing a lot more processes than you need to.

Managing users

Add user

me@home:~$ useradd -c “John from Accounts” -m -s /bin/bash john

useradd lets you add new users. The very minimum that the command needs is a username but you generally need to specify a little more than just username.

Modify user

me@home:~$ usermod -u 3000 john

usermod lets you modify an existing user. The example shown here modifies the UID of user john. Similarly, other aspects of a user can be modified.

Delete user

me@home:~$ userdel --remove-all-files johnny

userdel lets you delete users. The –remove-all-files flag ensures that the files created by this user are also deleted.

Managing groups

Add group

me@home:~$ groupadd manager

groupadd command is used to create a new group.

Modify group

me@home:~$ groupmod -g 300 manager

groupmod command is used to modify an existing group.

Delete group

me@home:~$ groupdel manager

groupdel command is used to delete a group.

Tips and tricks

Using the command line can help you get things done faster. This section introduces some tips and tricks to help you along the way.

Globbing

Metacharacters like ? and * are special characters that let you match file and directory names without having to list them out.

me@home:~$ ls a* me@home:~$ ls a? me@home:~$ ls [ab]*

The first command matches all the files and directories that begin with a followed by any number of characters as * matches any number of characters. So, a, ab, abc, etc. are all valid matches as long as they begin with a.

The second command matches all the files and directories that begin with a followed by a single character as ? matches a single character. So, ab, ac, etc. are all valid matches as long as they begin with a.

The third command matches all the files and directories that begin with either a or b followed by any number of characters.

Redirection

By default, every command reads from the standard input and writes to the standard output. However, you can change that and redirect the output. For example, you can redirect your output to a file. Execute the following command to redirect the output of ls to a file.

me@home:~$ ls > file

The output of the command would be written to a file named “file”.

If you execute the command again, the previous output would be overwritten. You can append like so:

me@home:~$ ls >> file

This is redirection in its simplest form. You can also redirect from a file i.e. provide the contents of a file as an input to a command, or redirect standard error to a file. Here are more options to redirect output.

2> would redirect standard error to a file.

&> would redirect both standard output and standard error to a file.

< would redirect the contents of a file to the command i.e. provide it as an input.

Piping

Piping is also a form of redirection. However, with piping, the output of one command is sent to another command for processing. You can chain multiple commands using the pipe operator which is a vertical bar (|) found above the \ key.

For example, if you want to scroll through the list of files in a directory, you could do so as follows:

me@home:~$ ls -al | less

Bang bang

Bang bang allows you to execute previous commands easily.

For example, here’s how you’d re-execute the last executed command.

me@home:~$ !!

You can also use pattern matching and wildcards in conjunction with bang bang. For example, to execute a previous command that started with letter “l” like less or ls, execute the following:

me@home:~$ !l

Brace expansion

Brace expansion lets you expand a set of characters. For example, if you want to create a number of files like “file1”, “file2”, and so on up to one 100, you can easily do so using brace expansion. Here’s how:

me@home:~$ touch file{1..100}

The contents of the brace would be expanded and appended with the word “file”. You can use brace expansion with other commands such as rm, etc. to remove files easily.

Auto completion

Autocompletion lets you type commands and file / directory names faster. Partially entering a command, file, or directory name and pressing tab key will either autocomplete what you are entering or provide you with suggestions if there are multiple options. For example, to change into one of the directories under the file system root, execute the following:

me@home:~$ cd /[TAB] bin/ dev/ lib32/ mnt/ run/ sys/...

How the suggestions for autocomplete behave depends on your shell. In BASH, the suggestions are simply printed on the standard output however other shells may let you choose one of the suggestions using the arrow keys.This brings us to the end of the guide.

Additional resources are listed in the next section.

Additional Resources

If you are new to the Linux operating system, take a look at the Linux Essentials course available at Linux Academy. The course will give you a basic understanding of Linux and give you a gentle introduction to the command line.