Linux Commands Handbook

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

SGSITS

Computer Engineering Department


Computer Programming
First Year 2021-2022 (nov-)

(LINUX HAND-BOOK)

Last update : Nov 1, 2021


Last update : Apr 6, 2022

_ _
| | (_)_ __ _ ___ __
| | | | '_ \| | | \ \/ /
| |___| | | | | |_| |> <
|_____|_|_| |_|\__,_/_/\_\

Chapter 1
Linux Basics.

Developer / Community : Linus Torvalds

Written in : C, Assembly language

OS family : Unix-like

Linux is an open-source operating system. It is like Windows, Mac, Android, etc.

Unix is also an operating system like Linux. It is a commercial OS. It consists of three
parts: Kernel, Shell and Programs. Most of the Unix and Linux commands are similar in
nature.
Our Linux tutorial includes all topics of Linux OS such as Linux commands, Directories,
Files, Man Pages, File Contents, File Permissions, shells, VI editor etc.

Chapter 2
Linux Commands.
Lecture Wise

Lecture - 1

1. ls - for listing files and directory

(ll, la, ls -l , ls -alt) try these also

2. mkdir => make directory


3. rmdir =>remove directory
4. rm => remove file
5. rm -rf => remove non empty directory
6. cat => cat filename to show its contents
7. nano (ctrl + x => to save)
8. clear => clear terminal
9. pwd => present working directory
10.less => less filename
11.more => more filename
12.man => manual , man ls

Lecture - 2
13. cp => for copy $ cp source destination
14. mv => for moving contents $ source destination
15. cal => calendar
16. date => date
17. cat > filename then ctrl^c
18. cat >> filename
19. touch
20. vi
21. echo “message”
22. echo “message to file” > filename.txt

Lecture - 3
23. ping $ ping google.com
24. ps
25. kill -9 process_id
26. Chmod => rwx, ‘a’ll , ‘g’roup , ‘o’wner , ‘u’ser ,
27. grep “pattern_to_match” filename
28. sudo apt install <package_name>
29. sudo apt remove <package_name>
30. who
31. whoami
32. passwd
33. reboot
34. exit

--------------------------------------------------------------------------------------------

35. for creating user as sgsits_username_cse000123


$ sudo useradd -m sgsits_username_cse000123

-----------------------------------------------------------------------------------------

36. for changing password of sgsits_username_cse000123


$ sudo passwd sgsits_username_cse000123

------------------------------------------------------------------------------------------

37. assigning a default shell for sgsits_username_cse000123


$ sudo chsh -s /bin/bash sgsits_username_cse000123

-------------------------------------------------------------------------------------

38. adding sgsits_username_cse000123 to sudo group , so


sgsits_username_cse000123 can install software

$ sudo usermod -a -G sudo sgsits_username_cse000123

-----------------------------------------------------------------------------

now , you can login to user sgsits_username_cse000123

via cli
39. sudo su sgsits_username_cse000123

via gui

$ swtich user

40. Pipe $ cat /etc/passwd | grep -i -n “hello”

*******************************************************************************************
A

apt Search for and install software packages (Debian/Ubuntu)

$ sudo apt install <package_name>


$ sudo apt remove <package_name>

apt-get Search for and install software packages


(Debian/Ubuntu) $ sudo apt install <package_name>

bash GNU Bourne-Again SHell

$ cat /etc/shells

cal Display a calendar


$ cal

cd Change Directory
$ cd .. // go to previous directory

$ cd <to_specific_path>

chmod Change access permissions


$ chmod a+x <filename>

clear Clear terminal screen


$ clear //

cp Copy one or more files to another location


$

D date Display or change the date & time $

dir Briefly list directory contents


$

dpkg Package manager (Debian/Ubuntu).


$ dpkg -i <pack_name>
$ dpkg --list // for listing softwares
E echo Display message on screen • $

exit Exit the shell


$

export Set an environment


variable

$ export
http_proxy=http://address:port

¯_(ツ)_/¯

groupadd Add a user security


group $

groupdel Delete a group


$

help Display help for a built-in command •

$ help

history Command History


$ history

htop Interactive process viewer


$ htop

kill Kill a process by specifying its PID


$ kill <p_id>

L logout Exit a login shell • $

ls List information about file(s)


$ ls
$ ls -l

make Recompile a group of programs

$ make

man Help manual


$ man <command_name>

mkdir Create new folder(s)


$ mkdir folder_name

mv Move or rename files or


directories $ mv src dest

passwd Modify a user password

$ passwd <user_name>

pwd Print Working Directory


$ pwd

reboot Reboot the system


$ reboot
rm Remove files
$ rm filename
$ rm -rf dir/

rmdir Remove folder(s)


$ rmdir dir

shutdown Shutdown or restart linux $

split Split a file into fixed-size


pieces

$ split filename
$ split -n 2 filename

sudo Execute a command as another user


$ sudo ...

tail Output the last part of a file

$ tail file_name

$ tail -n 2 file_name

time Measure Program running time


$ time program

useradd Create new user account

$ useradd new_user // syntax


userdel Delete a user account
$ userdel new_user // syntax

vi Text Editor

$ vi

W wc Print byte, word, and line counts $ wc filename

which Search the user's $path for a


program file $ which <command>

who Print all usernames currently


logged in

$ who

whoami Print the current user id and name


('id -un')

$ whoami

Chapter 3
USER AND GROUPS.
1. For adding group

$ sudo groupadd group_name // syntax

2. For adding user


$ sudo useradd user_name // syntax
$ sudo useradd user_1
$ sudo useradd user_2

3. For adding user to a group

$ sudo usermod -a -G group_name user_name //


syntax $ sudo usermod -a -G group_name user_1
$ sudo usermod -a -G group_name user_2

4. For user's group


$ id user_name // syntax
$ id user_1
$ id user_2

5. For deleting group

$ sudo groupdel group_name

Chapter 4
TEXT EDITORs.
Emacs Xemacs – a GUI-based version of Emacs.

vi – a mostly terminal-based text editor, very reliable.

vim – (vi improved) – a GUI-based version of vi.

A text editor, written by Bill Joy in 1976. Short for Visual Interface. It enables fast,
simple, and effective text editing mostly based on simple key bindings. It provides fast
and convenient moving around files and between files. One must learn a good number
of commands to be proficient in vi.

vi works in two modes: insert mode and command mode.

Command mode:

Allows you to do global operations like saving the file, searching for a string

and replacing it. Insert mode:

Everything you type in the text.

Vi is started with command mode


Switching modes

i : from command mode to insert mode

Esc : rom insert mode to command mode

Open a file (new or exitsting one)

$vi file_name

Save a file

$:w

Exit vi (without saving the file)

$:q!

Exit vi (and save the file)

$:wq $:x

Open a file (new or exitsting one)

vi file_name

Save a file

:w

Exit vi (without saving

the file) :q!

Exit vi (and save the

file) :wq :x

Chapter 5
GREP
search pattern

Search for 'hello' in main.c

$ grep 'hello' main.c

Search hello in any case (i.e. case insensitive search) flag = -i // for case insensitive
search $ grep -i 'hello' main.c
Search hello and world in any case flag = -i // for case insensitive search flag = -E // for
extended regular expression

$ grep -E -i 'hello|world' main.c

GENERAL

1. print lines begining with range of letters

grep ^[A-D] main.c

$ grep ^[#] main.c


$ grep ^[i] main.c

2. REGEX

//A regular expression or regex of short is a sequence of


characters that specifies a search pattern.

3. search for word which has any single character followed by ello

grep ".ello" demo.txt

4. AND, there is no AND so regex works

grep 'Manager.*Sales' employee.txt

5. AND & OR

grep 'Manager.*Sales\|Developer*Tech' employee.txt

6. begin with 1 and endswith C

grep '^1.*C$' file.txt

7. FLAGS // print everything that doesn't contain the query

grep -v ^Da* main.c


8. -i forgets about case sensitivity

grep -i ^DA main.c

9. show only the matched string, not the entire line in which it is

present within. grep -o "Meow" main.c

10. print the file containing the query including thos

within subdirs grep -r ^David ~/scripts-

x14.04/bash/*

11. print the name of the file(s) which matches the query

grep -l ^David ~/some_dir/*

12. count the number of matches

grep -c "stuff" main.c

13. show the line numbers of the matches

grep -n "go" demo.txt

14. search only for the full word

grep -w "of" main.c

15. print 3 lines after the match (-B for before the match & -C for

before and after) grep -A 3 "of" main.c


16. extended regex $ grep -o -E ".rld|.e" main.c

Chapter 6
PERMISSIONs.
LINUX is a multi user os.

There are three types of permissions in files and


folders in unix > Read (r)
> Write (w)
> Execute (x)

And, there is a classification of users called UGO (explained


bellow):

U ~> User (usually, owner)


G ~> Group (eg sudo group)
O ~> Others

When you run


$ ls -l

your output will be something like this:

-rwxrwxrwx@ 1 user staff


-rw-r--r-- 1 user staff
-r--------@ 1 user admin
drwxr-xr-x 3 user staff

How to read this? Where is a letter put a 1 and where is a - put a 0. Examples:

UGO

rwxrwxrwx

111111111

So, user, group and others can read, write and excute the file or folder

UGO

r w - r -- r - x

110100101
So, user can read and write, group can only read, finally other can

read and execute Codes :

Bin Decimal Representation


12 / 22
contents.markdown 9/27/2021

Binary Decimal codes

000 0 - - -

001 1 - - x

010 2 - w -

011 3 - w x

100 4 r - -

101 5 r - x

110 6 r w -

111 7 r w x

The syntax is something like this:

command : chmod --> change mode | premission

$ chmod u/permissions g/permissions o/permissions file[or /dir/]

So, if I run
$ chmod 777 file <=> rwx rwx rwx

everybody can do anything with file

Or I run

$ chmod 744 dir <=> rwx r-- r--

only user can read, write and execute, group and others

only read dir. Or run

$ chmod 200 file2 <=>

-w- --- ---

only you can write file2


MAKING FILE EXECUTABLE

$ chmod a+x file

Chapter 7
SED, AWK
SED

sed:

The sed command is a stream editor that works on streams of characters. It’s a more
powerful tool than grep as it offers more options for text processing purposes, including the
substitute command, which sed is most commonly known for.

Replace the first occurrence of a string in a file, and print the result: sed

's/find/replace/' filename sed 's/find/repalce/2' filename // repalce 2nd occurrence

of find

sed 's/find/repalce/g' filename // repalce all occurrences of find

sed '3 s/find/replace/' filename // replace at line number

To Delete a particular line say n in this example

$ sed 'nd' filename.txt // syntax $ sed '5d' filename.txt

To Delete a last line

$ sed '$d' filename.txt // syntax

To Delete line from range x to y

$ sed 'x,yd' filename.txt // syntax $ sed '3,6d' filename.txt

To Delete from nth to last line

$ sed 'nth,$d' filename.txt // syntax $ sed '12,$d' filename.txt

To Delete pattern matching line


$ sed '/pattern/d' filename.txt // syntax $ sed '/abc/d' filename.txt

AWK awk: The awk is a full-fledged programming language that is comparable to Perl. It
not only offers a multitude of built-in functions for string, arithmetic, and time manipulation
but also allows the user to define his own functions just like any regular scripting language.

Text processing,

Producing formatted text reports,

Performing arithmetic operations,

Performing string operations, and many more.

$awk [options] [file]

Print the fifth column in a space separated file: awk '{print $5}' filename

Print the second column of the lines containing "something" in a space separated file:
awk '/something/ {print $2}' filename $ awk '/Hello/ {print $2}' main.c

Let us create a file marks.txt which contains the serial number, name of the student,
subject name, and number of marks obtained.

1. roll_number_1 os 80
2. roll_number_1 compiler 90
3. roll_number_1 ds 87
4. roll_number_1 linux 85
5. roll_number_1 coa 89

Let us now display the file contents:

$ awk 'BEGIN{printf "Sr No\tName\tSub\tMarks\n"} {print}' marks.txt

(OR)

$ awk '{print}' marks.txt

Printing Lines with More than 10 Characters

$ awk 'length($0) > 10' marks.txt

prints the first word of each line

$ awk -F: '{print $1}' /etc/passwd

prints the second column

$ awk '{print $2}' marks.txt

prints the more than one column


$ awk '{print $1,$2,$3}' marks.txt

The awk command special expressions:

There two special expressions, “BEGIN” and “END”:

BEGIN: To perform an action before data is processed

END: To perform an action after the data is processed

$awk ‘BEGIN {print “Processing has begun”}; {print $2}; END {print “Processing has ended”}’
marks.txt

Chapter 8
Basic Shell Scripting
Exercise_1 - Write a shell script that prints “Hello World” on the screen

\#!/bin/bash

echo “Hello World”

Exercise_2 - Modify the shell script from exercise 1 to include a variable. The variable will
hold the contents of the message “Hello World”

\#!/bin/bash

NAME=”Hello World”

echo $NAME

Exercise_3 - Store the output of the command “hostname” in a variable. Display “This
script is running on .” where “” is the output of the “hostname” command.

\#!/bin/bash
HOSTNAME=$(hostname)
echo “This script is running on $HOSTNAME”

Exercise_3 - Loop and expressions.

for i in {1..10}; do sum=$(($i + $i)); echo $sum; done

Exercise_4 - User input.

#/bin/bash
read -p "Your name: " name
echo "Hello $name"

Exercise_5 - Custom downloader.

#/bin/bash
read -p "Webpage address: " webpage
#echo "Hello $webpage"
wget --no-check-certificate --content-disposition $webpage

Final summary
So, finally we worked with

LINUX OS. outcomes:

1. Working with Linux Os.

2. Working with CLI.

3. Bash Scripting.

4. ...
Chapter 9
Gnu Coding Standards
Write Better Codes
C

Type 1

#include<stdio.h>
void main()
{
printf("Hello World\n");
}

Type 2

#include<stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}

Type 3

#include<stdio.h>
int main(int argc, char *argv[])
{
printf("Hello World\n");
return 0;
}

Type 4
#include<stdio.h>
// Entry point function
int // return type
main(int argc, char *argv[]){
printf("Hello World\n"); // main
definition
return 0;
}

Type 5

#include<stdio.h>
// declaration
void print_message();
void
print_message(){
printf("Hello World\n");
}

int
main(int argc, char
*argv[])
{ print_message();
return 0;
}

Type 6

#include<stdio.h>
// declaration
void print_message(char *);

// def
void
print_message(char
*message){
printf("%s\n",
message);
}

int
main(int argc, char
*argv[])
{ print_message("Hello
World"); return 0;
}

Type 7

#include<stdio.h>
// declaration
void print_str(char *);
void print_int(int);
void print_float(float);

void
print_str(char
*message){
printf("%s\n",
message);

void
print_int(int i){
printf("%i\n", i);
}

void
print_float(float f){
printf("%f\n",f);
}

int
main(int argc, char
*argv[])
{ print_str("Hello
World"); print_int(50);
print_float(2.5);
return 0;
}
Chapter - 10

------------------------------------------------------
C Header file and
Make Header Files
Create your own Header

Files Make

Redirections :

Input redirect :

$ ls < $(pwd)

$ tr < abc.txt > out.txt

Output redirect

$ ls -l > ok.txt

$ history > his.txt

You might also like