Introduction to Linux & Terminal Commands - Complete Blog for Beginners

Introduction to Linux & Terminal Commands - Complete Blog for Beginners

Get introduced to various command-line operations and understand concepts in very Easy + Beginner friendly langua

As a programmer it is essential to learn to interact with the Operating System (OS) of your computer, and for that using a command-line interface over a GUI has some advantages -

  • Provides more efficient management of systems on scale.
  • It's ability to store scripts to automate regular tasks.
  • You can have control over OS/Applications with different levels of access aka Granular control.

Linux boasts a powerful command line with a wider range of commands, is faster, works everywhere (including servers) and 90% of all cloud infrastructure and hosting services use Linux? 🤯 For this reason alone, it is crucial to be familiar with popular Linux commands.

Linux is an operating system's kernel cloned from Unix, so If you're a Mac user the command line interpreter in Mac OS is usually bash, just like in Linux, but you can run other shells if you like. I would suggest to use any terminal emulator like iTerm which has some really nice features and customizing options available. If you are a Windows user, you would have to download and install Windows Subsystem for Linux (WSL). This is a compatibility layer for running Linux binary executables natively on Windows.

Some Terminologies

Command-line interface (CLI)

A command-line interface (CLI) processes commands to a computer program in the form of lines of text, like we operate a computer with mouse, similarly in this we give commands in a shell to our operating system to perform specified actions. The other one that we use normally is a Graphical-user interface (GUI).

Shell

The shell is the layer of programming that understands and executes the commands a user enters. In some systems, the shell is called a command interpreter. As the name suggests, it's the outer layer of an operating system, a shell can be contrasted with the kernel, the operating system's inmost layer or core of services.

Kernel

The kernel is the essential center of a computer operating system (OS). It is the core that provides basic services for all other parts of the OS. It is the main layer between the OS and hardware, and it helps with process and memory management, file systems, device control and networking.

Distros

Different versions of Linux are called ‘distros’. Anyone can create their own Linux distro, some popular available Linux Distros are - Ubuntu, Fedora, Arch.

Terminal

Your ‘terminal’ is the primary way you’ll interact with Linux. This is where you enter all of your commands, and the interface tends to be very straightforward. However, you can also opt to use terminal emulators, which are software options that provide you with a more user-friendly interface.

Root

Linux OSs have a built-in system where user roles are defined. Each user has a designated role, with varying levels of permissions. For example, if you’re a guest, you won’t be able to modify the OS’s core files.

A ‘root’ account, on the other hand, is like a top level user with full access to every command and file in the system. That is to say, if you’re a root user, you can do just about anything you want.

Package Manager

When it comes to Linux, you install ‘packages’ rather than programs. Typically, you’ll do this through the terminal. A ‘package manager’ is a tool that provides you with a graphical interface to help you find new packages, then install, update, and even configure them.

Binaries

A ‘binary’ file isn’t composed of regular text, but rather is made up of computer code. In many cases, binary files on Linux are executable, much like Windows .exe files. In other words, they can be run in order to perform some task or functionality.

Basic Linux Commands

Let's begin with some pretty basic commands that are used often.

ls - List all files in the folder

➜  Newfolder ls
'New Text Document (2).txt'  'New Text Document.txt'

This displays the directories and files in my Newfolder directory.

mkdir - Make directory

➜  Newfolder mkdir folder

This make a directory named "folder" inside the Newfolder

cd - Change directory

➜  Newfolder cd folder
➜  folder

➜  folder cd ..
➜  Newfolder 

➜  Newfolder cd
➜  ~
  • cd folder - This will switch directory to folder inside Newfolder.

  • cd .. - To go back to parent directory.

  • cd - To navigate to home directory.

pwd - print working directory

➜  Newfolder pwd
/mnt/f/Newfolder

pwd command displays the current working directory you are in.

touch - creates a file

Newfolder touch names.txtNewfolder ls

folder
names.txt

touch creates a file (not a directory) in the current directory.

Vi Editor

Let's talk about The VI editor. It is the most popular and classic text editor in the Linux family. With vi editor you work on the content of any text file directly in your terminal.

Nowadays, there are advanced versions of the vi editor available, and the most popular one is VIM which is Vi Improved. Some of the other ones are Elvis, Nvi, Nano, and Vile. It is wise to learn vi because it is feature-rich and offers endless possibilities to edit a file.

To work on VI editor, you need to understand its operation modes. They can be divided into two main parts.

Vi Command Mode

  • The vi editor opens in this mode, and it only understands commands
  • In this mode, you can, move the cursor and cut, copy, paste the text
  • This mode also saves the changes you have made to the file
  • Commands are case sensitive. You should use the right letter case.

Vi Insert Mode

  • This mode is for inserting text in the file.
  • You can switch to the Insert mode from the command mode by pressing ‘i’ on the keyboard
  • Once you are in Insert mode, any key would be taken as an input for the file on which you are currently working.
  • To return to the command mode and save the changes you have made you need to press the Esc key

Saving and Closing the file

  • Shift+zz – Save the file and quit
  • :w – Save the file but keep it open
  • :q – Quit without saving
  • :wq – Save the file and quit

Note - You should be in the command mode to exit the editor and save changes to the file.

cat - concatenate files and print on the standard output

➜  Newfolder cat names.txt
anas khan
atharva
anuj

➜  Newfolder cat > hello
creating hello file with cat command
^C
➜  Newfolder cat hello
creating hello file with cat command

➜  Newfolder cat names.txt hello > combined.txt
➜  Newfolder cat combined.txt
anas khan
atharva
anuj
creating hello file with cat command

With cat command you can display the contents of a file.

  • cat > hello - It will create a file name "hello" and as you press enter you will be able to write the file. After doing that, let's say I entered creating " hello file with cat command ". To exit writing the file press ctrl + C.

  • cat names.txt hello > combined.txt - This will merge the contents of 2 files - names.txt, hello into one - combined.txt and will display it.

echo - print

➜  Newfolder echo "Hello World"
Hello World

➜  Newfolder echo "Hello World" > helloworld.txt
➜  Newfolder cat helloworld.txt
Hello World

echo simply means print.

  • echo "Hello World" > helloworld.txt - will create a file "helloworld.txt" and overwrite it with text "Hello World"

man - an interface to the system reference manuals

➜  Newfolder man git

man command gives detailed description about a particular command.

cp - copy

➜  Newfolder cp names.txt names2.txt

➜  Newfolder cat names.txt
anas khan
atharva
anuj

➜  Newfolder cat names2.txt
anas khan
atharva
anuj➜  Newfolder man git

cp command makes a copy of a file, in this names.txt already existed and it created names2.txt.

mv - move

➜  Newfolder mv names2.txt folder/

➜  Newfolder mv names.txt renames.txt

mv command is used to move files

  • mv names2.txt folder/ - Moves names2.txt to directory "folder".

  • mv names.txt renames.txt - Basically renamed names.txt to renames.txt

rm - remove

Newfolder rm address.txt

rm is used to delete a file (permanently)

sudo - super user do

Sudo is the master key to your high-privilege admin tasks. Have you ever tried to edit a config file only to receive "Permission Denied" ? If so, that was because your user account did not have access to that file. You need root or sudo 'er access.

➜  Newfolder vi /etc/sudoers

"/etc/sudoers" [Permission Denied]

➜  Newfolder sudo vi /etc/address
password:

For example, if you want to edit an important configuration file, you might use vi /etc/sudoers: When you do, though, you would be met with "Permission Denied" error, or an equivalent:

Trying that with sudo - You would be prompted for your user account's password. After entering a correct credential, you would then be given read/write access to the file.

df - displays free disk space

➜  Newfolder df

➜  Newfolder df -m  // in Mbs

➜  Newfolder df -g  // in Gbs

df reports file system disk space usage.

Head - output the first part of files

➜  Newfolder head combined.txt
anas khan
atharva
anuj
creating hello file with cat command
rahul
keshav
rizwan
harris
cletus
john

➜  Newfolder head -n 2 combined.txt           // first 2 lines
anas khan
atharva

head command allows you to check first part of files, by default it displays top 10 lines of files and you can also specify as shown.

Tail - output the last part of files

➜  Newfolder tail combined.txt

➜  Newfolder tail -n 2 combined.txt           // first 2 lines
anas khan
atharva

head command allows you to check first part of files, by default it displays top 10 lines of files and you can also specify as shown.

diff - compare files line by line

Newfolder diff combined.txt helloworld.txt

find - search for files in a directory hierarchy

➜  Newfolder find .       // all files in current directory

➜  Newfolder find ..      // all files in previous directory   

➜  Newfolder find . -type d       // only directories in current dir

➜  Newfolder find . -type f       // only files in current dir

➜  Newfolder find . -type f -name "names*"       // files starting with names..

➜  Newfolder find . -type f -name "*.txt"             // files ending with ...txt

➜  Newfolder find . -type f -iname "*.txt"      // -i avoids case sensitivity

➜  Newfolder find . -type f -mmin -20      // files modified less than 20 minutes ago

➜  Newfolder find . -type f -mmin +15      // files modified more than 15 minutes ago

➜  Newfolder find . -type f -mmin +2 -mmin -10      //  "--" less than 10 & more than 2 minutes ago

➜  Newfolder find . -type f -mtime -10      // files modified less than 10 days ago

➜  Newfolder find . -type f -maxdepth 2      // files in up to 2 subfolder level

➜  Newfolder find . -size  +1K      // files of size > 1 kb

➜  Newfolder find . -empty          //  empty files

* in starting or ending basically means that anything can come over there while searching for multiple files. -f stands for force! Sometimes when you execute a command, it fails or prompts you for additional input. This may be an effort to protect the files you are trying to change or inform the user that a device is busy or a file already exists.

Changing file permissions

To know about file permissions :


  Newfolder ls -l renames.txt
-rwxrwxrwx 1 muhammedanaskhan muhammedanaskhan 23 Feb 24 07:10 renames.txt

Note that -rwxrwxrwx stands for ( r - read ; w = write ; x = execute )

file_permissions.png

The user, group and other permissions can also be set and denoted in numerical form as :

rwx-permissions.png

Let's take a look on how to change the permissions of the file-


➜  Newfolder chmod u=rwx,g=rx,o=r renames.txt

➜  Newfolder ls -l renames.txt
-rwxrxr 1 muhammedanaskhan muhammedanaskhan 23 Feb 24 07:10 renames.txt

Using numerical method :


➜  Newfolder chmod 777 renames.txt

➜  Newfolder ls -l renames.txt
-rwxrwxrwx 1 muhammedanaskhan muhammedanaskhan 23 Feb 24 07:10 renames.txt

chown - change file owner and group

The chown command changes user ownership of a file, directory, or link in Linux. Every file is associated with an owning user or group. It is critical to configure file and folder permissions properly.

➜  Newfolder sudo chown root renames.txt

In this command we are changing user to root, which is the user name or account that by default has access to all commands and files on a Linux

whoami - print effective userid

know current user with this command

➜  Newfolder whoami
muhammedanaskhan

Grep

Global regular expression print

grep is a command-line utility for searching plain-text data sets for lines that match a regular expression. Basically it is used to search data inside a file.

➜  Newfolder cat renames.txt
anas khan
atharva
anuj

➜  Newfolder grep "anuj" renames.txt
anuj

➜  Newfolder grep "rahul" renames.txt   // no output as "rahul" does not exist
➜  Newfolder

history - GNU History Library

By default, the history command will show you the last five hundred commands you have entered. Here we are piping " ls -l " command history through grep command

➜  Newfolder history | grep "ls -l"
  579  ls -l
  784  ls -l renames.txt
  788  ls -l renames.txt
  790  ls -l renames.txt

Alias

Aliases are like custom shortcuts used to represent a command (or set of commands) executed with or without custom options. It is used to replace a string that invokes a command in the linux shell with another user defined string.

We can create temporary or permanent alias. If you open new terminal session, the temporary alias will no longer be available. If you wish to save your aliases across sessions you will need a permanent alias.

Temporary Alias

➜  Newfolder alias wr=”cd /var/www/html”

You can then use "wr" shortcut to go to the webroot directory. The problem with that alias is that it will only be available for your current terminal session.

Permanent Alias

To keep aliases between sessions, you can save them in your user’s shell configuration profile file. This can be:

  • Bash – ~/.bashrc
  • ZSH – ~/.zshrc
  • Fish – ~/.config/fish/config.fish
➜  Newfolder sudo vi ~/.zshrc
[sudo] password for muhammedanaskhan:
➜  Newfolder

After entering the file via vi just add :

alias gp ="git push"

Terminal shortcuts

  • ctrl A - move cursor to beginning of line
  • ctrl E - move cursor to end of line
  • ctrl K - delete everything after cursor
  • ctrl L - clear screen
  • Tab - auto complete

Using multiple commands in a line

➜  Newfolder ls ; cat renames.txt ; cd ..

'New Text Document (2).txt'  'and print on the standard output:q'   folder   helloworld.txt   renames.txt
'New Text Document.txt'       combined.txt                          hello    names.tx

anas khan
atharva
anuj

➜  f

seperate commands using ;

wget

Wget is the non-interactive network downloader which is used to download files from the server even when the user has not logged on to the system and it can work in the background without hindering the current process.

➜  f wget http://www.africau.edu/images/default/sample.pdf

--2022-02-24 12:51:52--  http://www.africau.edu/images/default/sample.pdf
Resolving www.africau.edu (www.africau.edu)... 104.21.63.175, 172.67.148.215, 2606:4700:83bd:a3eb:ffc5:55:98ec:c766
Connecting to www.africau.edu (www.africau.edu)|104.21.63.175|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3028 (3.0K) [application/pdf]
Saving to: ‘sample.pdf’

sample.pdf                    100%[=================================================>]   2.96K  --.-KB/s    in 0s

2022-02-24 12:51:53 (104 MB/s) - ‘sample.pdf’ saved [3028/3028]

➜  f

Zip

Newfolder zip file.zip renames.txt

Zipping renames.txt as file.zip

Unzip

Newfolder unzip file.zip

Hostname

show the system's host name

  Newfolder hostname
DESKTOP-B6SBA9A

  Newfolder hostname -i //ip address
127.0.1.1

Add a user

➜  Newfolder sudo useradd User
[sudo] password for muhammedanaskhan:

➜  Newfolder sudo passwd User      //set password
New password:
Retype new password:
passwd: password updated successfully

Delete user

➜  Newfolder sudo userdel User

Get OS information

➜  Newfolder cat /etc/os-release

NAME="Ubuntu"
VERSION="20.04.3 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.3 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal

Infor of CPU Architecture

  Newfolder lscpu

Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   39 bits physical, 48 bits virtual
CPU(s):                          4
On-line CPU(s) list:             0-3
Thread(s) per core:              2
Core(s) per socket:              2
Socket(s):                       1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           142
Model name:                      Intel(R) Core(TM) i3-7020U CPU @ 2.30GHz
Stepping:                        10
CPU MHz:                         2304.000
BogoMIPS:                        4608.00
Hypervisor vendor:               Microsoft

User and group id

➜  Newfolder id

uid=1000(muhammedanaskhan) gid=1000(muhammedanaskhan) groups=1000(muhammedanaskhan),4(adm),20(dialout),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),117(netdev),1001(docker)

Networking commands

  hp nslookup google.com  //  about website ip adress
Server:         172.24.64.1
Address:        172.24.64.1#53

Non-authoritative answer:
Name:   google.com
Address: 142.250.71.46
Name:   google.com
Address: 2404:6800:4007:808::200e
hp netstat        // all ports that are currently listening

Cut

Used to cut selected portion from each line of a file

➜  Newfolder cut -c 1-2 renames.txt
an
at
an

From index 1 to 2 print letters from each line of the file.

Working with operators


➜  Newfolder ping google.com &  // & in the end - run process in background

To kill the process


  Newfolder ps
9345 ping google.com

  Newfolder kill 9345

&& Operator

➜  Newfolder echo "first" && echo "second"

first
second

Second command will only execute if first executes successfully

|| Operator

➜  Newfolder kjahsdjkhsd || echo "run"

zsh: command not found: kjahsdjkhsd
run

Second command will only execute if first fails

{} Operator

It is a combination operator

➜  Newfolder echo "hey" && { echo "hi" ; echo "am good" }

hey
hi
am good

>> Operator

➜  Newfolder echo "added name" >> renames.txt

➜  Newfolder cat renames.txt

anas khan
atharva
anuj
added name

This will basically append output of first command to other

> Operator

➜  Newfolder echo "added name" > renames.txt

➜  Newfolder cat renames.txt

added name

This will override file