Linux Administration:Command Based

[root@localhost~]# root -->user name(logged in)

localhost -->Machine Name

~(tild) -->Home Dir

$ --> Any User(normal Account)

# --> Root User/Super User/Admin User

Linux File Hierarchy Structure

linux-directory

1. /bin :

Contains binary executables,Command use in single-user modes, Commands used by all the users e.g. ps, ls, ping, grep, cp etc.

2. /boot :

Boot loader files, e.g., kernels, initrd.
Kernel initrd, vmlinux, grub files are located under /boot e.g. initrd.img-2.6.32-24-generic, vmlinuz-2.6.32-24-generic.

3. /dev :

These include terminal devices, usb, or any device attached to the system.

Example: /dev/tty1, /dev/usbmon0, /dev/null.

4. /etc :

Contains configuration files required by all programs.

Contains startup and shutdown shell scripts used to start/stop individual programs e.g. /etc/resolv.conf, /etc/logrotate.conf.

5. /home :

Users’ home directories, containing saved files, personal settings, etc.

6. /lib:

Libraries essential for the binaries in /bin/ and /sbin/.

Library filenames are either ld* or lib*.so.*

Example: ld-2.11.1.so, libncurses.so.5.7

7. /media:

Mount points for removable media such as CD-ROMs (appeared in FHS-2.3).

8. /mnt :

Temporarily mounted filesystems.Temporary mount directory where sysadmins can mount filesystems.

9. /opt :

Optional application software packages.Contains add-on applications from individual vendors.

10. /sbin :

Essential system binaries, e.g., fsck, init, route.Just like /bin, /sbin also contains binary executables.Example: iptables, reboot, fdisk, ifconfig, swapon.

11. /srv :

Site-specific data served by this system, such as data and scripts for web servers, data offered by FTP servers, and repositories for version control systems.E.g. srv stands for service,Contains server specific services related data.

12. /tmp :

Temporary files. Often not preserved between system reboots and may be severely size restricted.DIR are created by system and users.Files under this directory are deleted when the system is rebooted.

13. /usr :

Secondary hierarchy for read-only user data; contains the majority of (multi-)user utilities and applications.

  • Contains binaries, libraries, documentation, and source-code for second level programs.

  • /usr/bin contains binary files for user programs. If you can’t find a user binary under /bin, look under /usr/bin. For example: at, awk, cc, less, scp

  • /usr/sbin contains binary files for system administrators. If you can’t find a system binary under /sbin, look under /usr/sbin. For example: atd, cron, sshd, useradd, userdel

  • /usr/lib contains libraries for /usr/bin and /usr/sbin

  • /usr/local contains user’s programs that you install from source. For example, when you install apache from source, it goes under /usr/local/apache2

  • /usr/src holds the Linux kernel sources, header-files and documentation.

14. /proc:

Virtual filesystem providing process and kernel information as files. In Linux, it corresponds to a procs mount.

  • Contains information about system process with particular pid.

Commands:

Chcon :Change file SELinux Security Context.

1. "su" command

  • Switches to the specified user's account and it will inherit the original user's environment variables to target user.

  • The current working directory, environment variables, and shell remain unchanged.

  • Example: su root

2. "su -" command

  • Switches to the specified user's account, but does not inherit the original user's environment variables instead it resets all environment variables and creates them again.

  • The current working directory is changed to the target user's home directory.

  • Example: su - root

Command Syntax in Linux: command [options]" and then "<arguments>"

Help(man-->manual)

Syntax: man <command name>

e.g man lsblk,man cd ,man sshd ,man route,updatedb ,

Small Description: e.g. whatis route

Location: whereis route

Working With Directory in Linux

PWD:The pwd command writes to standard output the full path name of your current directory (from the root directory).

cd ~: go back to home dir.

cd -:go back to previous loc(dir).

cd /:main dir

. -->current dir

..-->parent dir

cd /var/log (absolute path)

cd log (relative path)

auto path completion(tab)

1.ls Command

OptionsDescription
ls -alist all files including hidden file starting with '.'.
ls -dlist directories - with ' */'.
ls -llist with long format - show permissions.
ls -FAppend indicator (one of */=>@
ls -lhThis command will show you the file sizes in human readable format.
ls -rlist in reverse order.
ls -ilist file's inode(index) number.
ls -ltrView Reverse Output Order by Date.
ls -tsort by time & date.
ls -nIt is used to print group ID and owner ID instead of their names.
ls -mA list of entries separated by commas should fill the width.
ls -gThis allows you to exclude the owner and group information columns.
ls -qForce printing of non-graphic characters in file names as the character `?';.
ls -QPlace double quotations around the entry names.

ls -lh-->human redable space

ls -ld <path> (dir details)

  1. ls - The most frequently used command in Linux to list directories

  2. pwd - Print working directory command in Linux

  3. cd - Linux command to navigate through directories

  4. mkdir - Command used to create directories in Linux

  5. mv - Move or rename files in Linux

  6. cp - Similar usage as mv but for copying files in Linux

  7. rm - Delete files or directories

  8. touch - Create blank/empty files

  9. ln - Create symbolic links (shortcuts) to other files

  10. cat - Display file contents on the terminal

  11. clear - Clear the terminal display

  12. echo - Print any text that follows the command

  13. less - Linux command to display paged outputs in the terminal

  14. man - Access manual pages for all Linux commands

  15. uname - Linux command to get basic information about the OS

  16. whoami - Get the active username

  17. tar - Command to extract and compress files in Linux

  18. grep - Search for a string within an output

  19. head - Return the specified number of lines from the top

  20. tail - Return the specified number of lines from the bottom

  21. diff - Find the difference between two files

  22. cmp - Allows you to check if two files are identical

  23. comm - Combines the functionality of diff and cmp

  24. sort - Linux command to sort the content of a file while outputting

  25. export - Export environment variables in Linux

  26. zip - Zip files in Linux

  27. unzip - Unzip files in Linux

  28. ssh - Secure Shell command in Linux

  29. service - Linux command to start and stop services

  30. ps - Display active processes

  31. kill and killall - Kill active processes by process ID or name

  32. df - Display disk filesystem information

  33. mount - Mount file systems in Linux

  34. chmod - Command to change file permissions

  35. chown - Command for granting ownership of files or folders

  36. ifconfig - Display network interfaces and IP addresses

  37. traceroute - Trace all the network hops to reach the destination

  38. wget - Direct download files from the internet

  39. ufw - Firewall command

  40. iptables - Base firewall for all other firewall utilities to interface with

  41. apt, pacman, yum, rpm - Package managers depending on the distro

  42. sudo - Command to escalate privileges in Linux

  43. cal - View a command-line calendar

  44. alias - Create custom shortcuts for your regularly used commands

  45. dd - Majorly used for creating bootable USB sticks

  46. whereis - Locate the binary, source, and manual pages for a command

  47. whatis - Find what a command is used for

  48. top - View active processes live with their system usage

  49. useradd and usermod - Add new user or change existing users data

  50. passwd - Create or update passwords for existing users

Cat command in Linux with examples

1) To view a single file

$cat filename

2) To view multiple files

$cat file1 file2

3) To view contents of a file preceding with line numbers

$cat -n filename

4) Create a file

$ cat > newfile

5) Copy the contents of one file to another file.

$cat [filename-whose-contents-is-to-be-copied] > [destination-filename]

6) Cat command can suppress repeated empty lines in output

$cat -s reg.txt

7) Cat command can append the contents of one file to the end of another file.

$cat file1 >> file2

8) Cat command can display content in reverse order using tac command.

 $tac filename

9) Cat command can highlight the end of line.

$cat -E "filename"

10) If you want to use the -v, -E and -T option together, then instead of writing -vET in the command, you can just use the -A command line option.

$cat -A  "filename"

11) Cat command to open dashed files.

$cat -- "-dashfile"

12) Cat command if the file has a lot of content and can’t fit in the terminal.

$cat "filename" | more

13) Cat command to merge the contents of multiple files.

$cat "filename1" "filename2" "filename3" > "merged_filename"

14) Cat command to display the content of all text files in the folder.

$cat *.txt

15) Cat command to write in an already existing file.

$cat >> reg.txt
The newly added text.

cd Command in Linux with Examples

cd [directory]

How to move inside a subdirectory in Linux

cd [directory_name]

ls = To display all the files and directories in the current location (directory)

pwd = to check the current location path or we can say the current directory name

Using / as an argument in cd command in Linux

By using / as an argument in cd we can change the directory to the root directory. The root directory is the first directory in your filesystem hierarchy.

Syntax:

cd /

How to move inside a directory from a directory

cd dir_1/dir_2/dir_3
cd Documents/geeksforgeeks/example

How to move in home directory from any location in Linux System

~ this argument is used in cd command to change directory to the home directory from any location in Linux System.

Syntax:

cd ~

cd

How to move to parent or one level up from current directory in Linux

Syntax:

cd ..

cd ..

Use of cd “dir name” command in Linux

This command is used to navigate to a directory with white spaces. Instead of using double quotes we can use single quotes then also this command will work.

cd "dir name"

Here, replace “dir name” with the directory name you want.

For Example: If we want to move to “dir name” = “My songs”. We use the following command.

cd "My songs"

cd “My songs”

We can also use \ this in between if we don’t want to use double or single quotes.

cd My\ songs

cd My\ songs

cat > text.txt
input to file/overlap
cat >> text.txt
Concatenation
cat text1.txt text2.txt text3.txt > merge.txt
Merging the files

mkdir command in Linux with Examples

mkdir command in Linux allows the user to create directories (also referred to as folders in some operating systems). This command can create multiple directories at once as well as set the permissions for the directories.

Syntax:

mkdir [options...] [directories ...]

Options available in mkdir

1) –help: mkdir –help

mkdir --version

mkdir –version

3) -v or –verbose:

It displays a message for every directory created.
Syntax:

mkdir -v [directories]

mkdir -v [directories]

4) -p:

A flag which enables the command to create parent directories as necessary.

mkdir -p [directories]
mkdir -p first/second/third

-p option

5) -m:

This option is used to set the file modes, i.e. permissions, etc. for the created directories. The syntax of the mode is the same as the chmod command.
Syntax:

mkdir -m a=rwx [directories]

mkdir -m a=rwx [directories]

mkdir [directorie_name]

2) How to create a directory with verbose output using mkdir command?

mkdir -v [directory_name]

3) How to create multiple directories using mkdir command?

mkdir [directorie_name_1] [directorie_name_1] [directorie_name_1] .......

4) How to resolve permission denied error in mkdir command?

sudo mkdir dir_name

5) Creating multiple directory inside a directory?

mkdir dir_name/{dir1,dir2,dir3}

rmdir command in Linux With Examples

The rmdir command is useful when you want to remove the empty directories from the filesystem in Linux.

rmdir <options> <directory>
rmdir --help

rmdir—help-option

The above command displays the various options such as:

  • -p: This option removes the directory, including all its ancestors

  • -v, –verbose: Displays verbose information for every directory.

  • –ignore-fail-on-non-empty: This option does not report a failure that occurs because a directory is non-empty.

  • –version: This option displays the version information and exit.

Example 1: The Basic rmdir Command

rmdir mydir1 mydir2 mydir3 .....
rmdir LINUX INFO DETAIL

Example 2: The -p Option

You can use the -p option with the rmdir command to delete a directory, including all the subdirectories:

rmdir -p mydir1/mydir2/mydir3/...../mydirN
rmdir -p LINUX/mydir1/mydir2/mydir3

Example 3: The -v Option

If you want the terminal to display the message after removing the directory, you can use the -v option with the rmdir command:

rmdir -v dir1 dir2 dir3

Let’s now delete the LINUX, INFO, and DETAIL directories and display the message after their successful removal:

rmdir -v LINUX INFO DETAIL
rmdir: removing directory, 'LINUX'
rmdir: removing directory, 'INFO'
rmdir: removing directory, 'DETAIL'

Example 4: Remove Multiple Directories With the Same Expression

ls 
LINUX1
LINUX2
LINUX3

rmdir -v LINUX*
rmdir: removing directory, 'LINUX1'
rmdir: removing directory, 'LINUX2'
rmdir: removing directory, 'LINUX3'

Example 5: The –ignore-fail-on-non-empty Option

Sometimes you get the following error while removing a directory through the rmdir command:

rmdir <option> <directory> 
rmdir: failed to remove 'dir1': Directory not empty

So, in this case, you can use the –ignore-fail-on-non-empty to ignore the occurrences due to the non-empty directories. For instance, let’s remove the LINUX directory that contains sub-directories:

rmdir  --ignore-fail-on-non-empty LINUX

cp command in Linux with examples

cp stands for a copy.

cp [OPTION] Source Destination
cp [OPTION] Source Directory
cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory

The first and second syntax is used to copy the Source file to the Destination file or Directory.
The third syntax is used to copy multiple Sources(files) to the Directory.
cp Src_file Dest_file
$ ls
a.txt

$ cp a.txt b.txt

$ ls
a.txt  b.txt
cp Src_file1 Src_file2 Src_file3 Dest_directory
$ ls
a.txt  b.txt  new

Initially new is empty
$ ls new

$ cp a.txt b.txt new

$ ls new
a.txt  b.txt

Note: For this case the last argument must be a directory name. For the above command to work, Dest directory must exist because cp command won’t create it.

Two directory names

cp -R Src_directory Dest_directory

In the above command, cp behavior depends upon whether Dest_directory exists or not. If the Dest_directory doesn’t exist, cp creates it and copies content of Src_directory recursively as it is. But if Dest_directory exists then copy of Src_directory becomes sub-directory under Dest_directory.

Options in cp

There are many options of cp command, here we will discuss some of the useful options: Suppose a directory named geeksforgeeks contains two files having some content named as a.txt and b.txt. This scenario is useful in understanding the following options.

$ ls folder_path
a.txt  b.txt
OptionDetailSyntaxExampleOutput
-i-i(interactive): i stands for Interactive copying. With this option the system first warns the user before overwriting the destination file. cp prompts for a response, if you press y then it overwrites the file and with any other option leaves it uncopied.cp -i [Source_file] [Destination_file]cp -i a.txt b.txtcat b.txtGFG
-b-b(backup): With this option cp command creates the backup of the destination file in the same folder with the different name and in different format.cp -b [Source_file] [Destination_file]cp -b a.txt b.txtlsa.txt b.txt b.txt~cat a.txt GFGcat b.txtGFG**cat b.txt~**GeeksforGeeks
-f-f(force): If the system is unable to open destination file for writing operation because the user doesn’t have writing permission for this file then by using -f option with cp command, destination file is deleted first and then copying of content is done from source to destination file.cp -f [Source_file] [Destination_file]cp -f a.txt b.txtls -l b.txt-r-xr-xr-x+ 1 User User 3 Nov 24 08:45 b.txt#User, group and others doesn’t have writing permission.#Without -f option, command not executed.cp a.txt b.txtcp: cannot create regular file ‘b.txt’: Permission denied#With -f option, command executed successfully.cp -f a.txt b.txt
-r or -R-r or -R: Copying directory structure. With this option cp command shows its recursive behavior by copying the entire directory structure recursively. Suppose we want to copy geeksforgeeks directory containing many files, directories into gfg directory (not exist).cp -r [Directory_name1] [Directory_name2]cp -r geeksforgeeks gfgls geeksforgeeks/a.txt b.txt b.txt~ Folder1 Folder2#Without -r option, errorcp geeksforgeeks gfgcp: -r not specified; omitting directory ‘geeksforgeeks’#With -r, execute successfully**cp -r geeksforgeeks gfgls gfg/**a.txt b.txt b.txt~ Folder1 Folder2
-p-p(preserve): With -p option cp preserves the following characteristics of each source file in the corresponding destination file: the time of the last data modification and the time of the last access, the ownership (only if it has permissions to do this), and the file permission-bits.cp -p [Source_file] [Destination_file]cp -p a.txt c.txtls -l a.txt-rwxr-xr-x+ 1 User User 3 Nov 24 08:13 a.txtcp -p a.txt c.txtls -l c.txt-rwxr-xr-x+ 1 User User 3 Nov 24 08:13 c.txt
*Copying using wildcard: The star wildcard represents anything i.e., all files and directories. Suppose we have many texts documents in a directory and want to copy it to another directory, it takes lots of time if we copy files 1 by 1 or command becomes too long if specify all these file names as the argument, but by using wildcard it becomes simple.cp *.txt [Destination Directory or file]cp *.txt Folder1#Initially Folder1 is empty.

mv command in Linux with examples

Two Distinct Functions of mv Command

    1. Renaming a file or directory.
    1. Moving a file or directory to another location

1) Renaming a file in Linux

mv [souce_file_name(s)] [Destination_file_name]

2) Moving a file in Linux

mv [source_file_name(s)] [Destination_path]

3) Moving Multiple files in Linux

mv [source_file_name_1] [source_file_name_2] [source_file_name_ .....] [Destination_path]
mv gfg_1 gfg_2 /home/jayeshkumar/jkj/

4) Renaming a directory in Linux

mv [source_directory_name(s)] [Destination_directory_name]

Options available in mv Command

1) -i (interactive)

The “-i” option makes the “mv” command ask for confirmation before overwriting an existing file. If the file doesn’t exist, it will simply rename or move it without prompting.

mv -i [source_file/directory_name(s)] [Destination_file/directory_name/path]

2) -f (Force)

mv prompts for confirmation overwriting the destination file if a file is write-protected. The -f option overrides this minor protection and overwrites the destination file forcefully and deletes the source file.

mv -f [source_file/directory_name(s)] [Destination_file/directory_name/path]

3) -n (no-clobber)

With -n option, mv prevents an existing file from being overwritten.

mv -n [source_file/directory_name(s)] [Destination_file/directory_name/path]
mv -n oldfile newfile

4. -b(backup)

With this option, it is easier to take a backup of an existing file that will be overwritten as a result of the mv command. This will create a backup file with the tilde character (~) appended to it.

mv -b [source_file/directory_name(s)] [Destination_file/directory_name/path]
mv -b first_file second_file

5. –version

This option is used to display the version of mv which is currently running on your system.

mv --version