Command Line Tips and Tricks

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/file1
me@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 
me@home:~$ ps 
PID TTY TIME CMD 
5252 pts/1 00:00:00 bash 
5318 pts/1 00:00:00 ps 
me@home:~$ ps -aux | less

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 
me@home:~$ vim &
[1] 5618
me@home:~$ kill -SIGKILL 5618
[1]+ Stopped vim
me@home:~$ jobs
[1]+ Killed vim

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.

https://linuxacademy.com/cp/modules/view/id/38

If you’d like to master the terminal, have a look at Mastering Linux Command Line:https://linuxacademy.com/cp/modules/view/id/10

To take your skills to the expert level, take a look at Linux by Example from Novice to Pros:

https://linuxacademy.com/cp/modules/view/id/19

Linux Academy provides a large library of in-depth online Linux training, and also gives access to many other online courses in topics like AWS, DevOps,Azure, OpenStack, and Big Data.



  • post-author-pic
    Johnny J
    12-21-2016

     @fasihxkhatib:  Nice guide!

  • post-author-pic
    Christopher G
    12-21-2016

    Really nice guide, Fasih. I love the formatting.

  • post-author-pic
    Daniel U
    12-26-2016

    Nice guide =)

  • post-author-pic
    Daniel S
    01-02-2017

    This is a great guide especially for anyone studying for an LPI Certification. Have you completed one of the LPI Certs so far?

  • post-author-pic
    Danny S
    01-04-2017

    Nice guide!

  • post-author-pic
    Evan L
    01-04-2017

    Nice Guide ... here are a few little tricks you might want to add that can save a lot of time!

    cp -a
    This is copy "all", which is just like recursive but tries to preserve permissions, ownerships, etc (best used by root).

    alias rm="rm -i"
    This one I have for root.  Make all "rm" commands interactive.  There is also "-I" which prompts for the whole batch rather than each file which some people may like better.

    Also for root:
    set -o noclobber
    This means that if you accidently use > rather than >> it won't "clobber" the original.   Basically, redirections can't destroy existing files.  Safe!

    And if you use vim, you've likely forgotten to "sudo" before editing a file and find out you can't save your changes!  You've likely heard of the w! command to ignore write permission, but if you aren't the owner, you're still stuck.  Add this to your .vimrc
    cmap w!! w !sudo tee "%" >/dev/null

    This gives you a ":w!!" command that will use sudo to save your file by piping it through tee.  It's a hack, but it will save you lots of typing.  Add it to your normal user account's .vimrc

    And I've personally switched to zsh from bash for my regular interactive shell.   The differences are subtle, but kinda nice once you get used to them.   Linux always has choices!

  • post-author-pic
    Conrado O
    01-04-2017

    Thank you!

  • post-author-pic
    Marcin S
    01-29-2017

    Hi,

    At the beggining, I want to thanks for the nice gude!
    I have supplement for 'BANG BANG' section. If you want to improve working with bash commandline you can use also combination 'Alt + .'. This will allow you to add last argument form the last command to command that you typing right now.
    Here is example:

    ls /this/is/a/very/very/long/path
    cd [Alt + .]

  • post-author-pic
    Ofrates C. S
    01-29-2017

    Thank you for sharing this information...

  • post-author-pic
    Barthélemy E
    01-30-2017

    Great! 

    You refresh my memory.

    thank you 

  • post-author-pic
    Linuxsys 6
    01-31-2017

    Hi,

    Just on this:

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

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

    Slight correction: a? will match 'a' following by any single character, but doesn't match 'a' itself.

    $ touch a ab ac abc
    $ echo a?
    ab ac
    $ ls a?
    ab ac

    Maybe just a typo in the ouput, or confusing globbing with regexes :)

  • post-author-pic
    Linuxsys 6
    01-31-2017

    ^^ *followed by

    expanded example:

    $ touch a aa ab ac abc a1
    $ ls a?
    a1 aa ab ac

  • post-author-pic
    Richard H
    02-16-2017

    Great guide, truly great guide. Thanks!

  • post-author-pic
    Shahan K
    02-16-2017

    Nice Work!

  • post-author-pic
    Fasih K
    02-23-2017

     @linuxsys666 Yes, you're right. I'll update that. Thanks for pointing out. :)

  • post-author-pic
    Brad B
    03-28-2017

    Nice!

  • post-author-pic
    Luis R
    04-27-2017

    Great, thanks!

  • post-author-pic
    Getraud M
    07-23-2017

    Thanks a lot! I just learned about the "!!" and the "brace formatting" in minutes!! Many thanks to you, very instructive. :)

  • post-author-pic
    Manish G
    09-08-2017

    Good Information, Thank you!

  • post-author-pic
    Maroko D
    02-06-2018

    Great information!! Loved the 'Brace expansion' trick.

  • post-author-pic
    Vijay G
    02-09-2018

    Thanks.is there a script or command line tirck to find hung processes on a linux server.

  • post-author-pic
    Mukarram H
    02-09-2018

    Awsm informatiom thnxxx

Looking For Team Training?

Learn More