☰ See All Chapters |
Linux Basic Operations
How do you create new folder in Linux?
Create single directory
mkdir directoryName
Create a nested structure of directories.
mkdir parentDirectoryName1/chilDirectoryName1/chilDirectoryName2
The above command works only if parentDirectoryName1/chilDirectoryName1 exists, otherwise you get error saying parent directories don’t exist.
To create all necessary parent directories at once, use the -p option
To create directory in a specific location us the below command where directory path should start from /, if directory path specified is not starting with / then it will create directory inside the current directory.
How to get the current directory path in Linux?
Get the current directory path using "pwd" command
How do you navigate to home directory in Linux?
To navigate to your home directory, execute the "cd ~" command.
How do you navigate one directory above the current directory in Linux?
To navigate to one directory above, execute the "cd ../" command.
How do you navigate to a specific directory in Linux?
Navigate to specific directory by using "cd /directoryPath"
Note: If directory path does not start with / then it navigates to the specified path starting from current directory.
How do you sort the contents of a file in Linux?
Sort a file alphabetically:
sort filename.txt
Sort numerically:
sort -n filename.txt
Sort by month:
sort -M filename.txt
Sorting in Reverse Order
sort -r filename.txt
Saving the Sorted Output
sort filename.txt -o sorted_filename.txt
Sort and remove duplicate lines:
sort -u filename.txt
How do you copy a directory and all its internal contents to another directory in Linux?
To copy a directory and all its contents to another directory in Linux, you can use the cp command with the -r (or --recursive) option. This option tells cp to copy directories recursively, including all their subdirectories and files. Never forget to use -i (interactive) option, otherwise if the destination_directory already contains files or directories with the same names, the cp command will overwrite them by default.
Here’s the basic syntax:
cp -r -i source_directory destination_directory
You can put both -i and -r flags together as below:
cp -ri source_directory destination_directory
Preserve File Attributes: To preserve file attributes like timestamps, ownership, and permissions, you can add the -p option:
cp -rp project backup
Verbose Output: If you want to see a detailed list of files being copied, use the -v (verbose) option:
cp -rv project backup
Handle Symbolic Links: If you have symbolic links and you want to copy the links themselves rather than the files they point to, you can use the -a (archive) option, which is a combination of -r, -p, and other options that handle links and preserve attributes:
cp -a project backup
How do you copy a file to another directory in Linux?
To copy file to any directory in Linux, you can use the cp command with the -i (interactive) option. Never forget to use -i (interactive) option, otherwise if the destination_directory already contains file with the same name, the cp command will overwrite them by default.
Here’s the basic syntax:
cp -i source_file path_to_destination_directory/
Note the path_to_destination_directory/ which end with forward slash.
Example: cp -i hello.txt app/data/files/
Preserve File Attributes: To preserve file attributes like timestamps, ownership, and permissions, you can add the -p option:
cp -p source_file destination_directory/
Verbose Output: If you want to see a detailed list of files being copied, use the -v (verbose) option:
cp -v source_file destination_directory/
Handle Symbolic Links: If you have symbolic links and you want to copy the links themselves rather than the files they point to, you can use the -a (archive) option, which is a combination of -r, -p, and other options that handle links and preserve attributes:
cp -a source_file destination_directory/
How do you rename directory in Linux? How do you move a directory and all its internal contents to another directory in Linux?
Renaming a directory in Linux is quite straightforward. You can use the mv (move) command to do this. Here’s the basic syntax:
mv old_directory_name new_directory_name
mv /home/user/oldname /home/user/newname
When to try mv command and if there is already a directory available then it will move the old directory to new directory, if new directory not available the old directory will be renamed to new directory.
For example, if you want to rename a directory from old_folder to new_folder, you would use:
mv old_folder new_folder
Make sure you have the necessary permissions to rename the directory. If you encounter any permission issues, you might need to use sudo.
sudo mv old_folder new_folder
How do you rename a file in Linux? How do you move a file to another directory in Linux?
Renaming a file in Linux is straightforward. You can use the mv (move) command for this purpose. The mv command is typically used to move files and directories, but it can also rename them.
Here's the basic syntax for renaming a file:
mv -i old_filename new_filename
-i flag is interactive option to avoid accidental overwriting. If you use the mv command without -i interactive flag to rename a file and the target filename (new_filename) already exists, the existing file will be overwritten without any warning by default.
How do you delete a file in Linux?
Using rm (Remove) Command
The rm command can be for deleting files. It’s powerful, but also a bit dangerous if used carelessly. Here’s how you can use it:
rm filename
If the file name includes a space, then you should put the file name along with its extension withing quotes. If file name do not have the space you can use file name without quotes.
If you don’t have write permissions on the parent directory, you’ll get an “Operation not permitted” error. If the file is write-protected, you’ll be prompted for confirmation before deletion.
To remove multiple files at once, list their names separated by spaces:
rm file1 file2 file3
If you want to delete files without any prompts (even if they’re write-protected), use the -f (force) option:
rm -f filename(s)
Using shred Command
When you delete a file using rm, only the reference (inode) is removed, not the actual data. If you want to securely delete the file’s content, consider shred:
shred -u filename
This overwrites the file’s data before removing it. Be aware that this process is irreversible!
Using unlink Command:
If you need to remove a single file, unlink is a lightweight option. This does not support directory deleteion.
unlink filename
Command | Purpose | How it Works | Usage Example | Data Overwriting | Security Implications | Scope |
rm | Remove files and directories | Deletes the file entry from the filesystem's directory structure. Data blocks are marked as free but not immediately overwritten. | rm filename.txt | Does not overwrite data | Data may be recoverable until overwritten by new data. | Can remove multiple files and directories; recursive options available. |
shred | Securely delete files | Overwrites file contents multiple times with random data before removing the file from the filesystem. | shred -u filename.txt | Overwrites data multiple times | Makes recovery much harder; less effective on SSDs or certain storage types. | Works on individual files; does not handle directories. |
unlink | Remove a single file | Removes the file's directory entry from the filesystem. Does not support directory removal or recursive deletion. | unlink filename.txt | Does not overwrite data | Data may be recoverable until overwritten by new data. | Only removes a single file; does not handle directories or recursion. |
How do you delete a directory and all its contents in Linux?
To delete a directory named my_directory and all its contents:
rm -r my_directory
If you want to delete the directory without being prompted for confirmation, you can add the -f (force) option:
rm -rf my_directory
If you want delete all the contents from current directory
rm -rf *
If you want delete all the contents from specific directory
rm -rf my_directory/*
How do you undo delete in Linux?
In Linux, once a file is deleted using commands like rm, it's generally not recoverable through traditional means because the rm command permanently removes files rather than moving them to a trash/recycle bin.
How do you get the size of a directory in Linux?
To get the size of all directory and its subdirectories from current directory:
du
To get the size of specific directory and its subdirectories from current directory:
du directoryName
To get the size of specific directory and its subdirectories:
du /path/to/directory
To display the size in a human-readable format (e.g., KB, MB, GB):
du -h /path/to/directory
To display only the total size of the directory and not its subdirectories:
du -sh /path/to/directory
How do you clear screen in Linux?
Clear screen executing "clear" command.
How do you list all files and folders in Linux?
To list all files and folders in Linux, you can use the ls command, which is one of the most commonly used commands for this purpose. Here are some useful variations of the ls command:
List files and directories in the current directory in same line:
ls
List files and directories recursively in all subdirectories in new line:
find .
List all files, including hidden files (those starting with a dot):
ls -a
List files with detailed information (permissions, owner, size, and modification date):
ls -l
Combine options to list all files with detailed information:
ls -la
List files in a specific directory:
ls /path/to/directory
List files recursively in all subdirectories:
ls -R
Sort files by modification time (newest first):
ls -lt
Display file sizes in human-readable format:
ls -lh
Detailed Listing with Hidden Files, Human-Readable Sizes, and Sorted by Modification Time:
ls -laht
How do you sort files and folders in Linux?
Alphabetically by name:
ls
Reverse order:
ls -r
By size:
ls -S
By modification time:
ls -t
How do you check Current Permissions of file/directory in Linux?
To check current permissions of all the files and folders in a directory
ls -l
To check current permissions of specific file/directory
ls -l folder_name
ls -l file_name.ext
First 10 characters indicates the permission as shown below
1 | "-" indicates a file "d" indicates directory "I" indicates a link |
2 | Read permissions for the owner of the file/folder, if – then owner don not have read permission |
3 | Write permissions for the owner of the file/folder, if – then owner don not have write permission |
4 | Execute permissions for the owner of the file/folder. if – then owner don not have execute permission |
5 | Read permissions for members of the group owning the file/folder, if – then members of the group don not have read permission |
6 | Write permissions for members of the group owning the file/folder, if – then members of the group don not have write permission |
7 | Execute permissions for members of the group owning the file/folder, if – then members of the group don not have execute permission |
8 | Read permissions for the other users of the file/folder, if – then other users don not have read permission |
9 | Write permissions for the other users of the file/folder, if – then other users don not have write permission |
10 | Execute permissions for the other users of the file/folder, if – then other users don not have execute permission |
How to change read only folder to write in Linux?
You should set necessary directory permissions. For directories they are:
read: permitted to view files and sub-directories in that directory
write: permitted to create files and sub-directories in that directory
execute: permitted to enter into a directory.
For files the situation is similar, it's quite obvious, so you can handle it on your own.
Numeric these permissions:
read - 4
write - 2
execute - 1
To edit permissions use chmod. Usage: chmod xyz <file or directory>
x - the sum of owner permissions
y - the sum of owner group permissions
z - the sum of rest users/groups permissions
Example:
$ chmod -R 664 /home/test/
Owner and members of owner’s group will have read and write access to /home/test and all it's sub-directories. The rest will have only read access. -R option here used to recursively set permissions.
Another example:
$ chmod 700 /home/test/video/
Will give only owner full access to /home/test/video directory. Others don not have any permission.
How do you create a file in Linux?
Using the touch command:
touch filename.extension
How do you create a text file in Linux?
Along with touch command you can use cat, echo, printf, nano, vi, vim commands if the file is text editable file like txt, bat, sh, csv etc…
Using the cat command:
cat > filename.txt
This command allows you to create a file and immediately start typing its contents. Press Enter after you are done with entering your text then press Ctrl+d to save and exit.
Using the echo command:
echo "Some text" > filename.txt
This command creates a file named filename.txt and writes “Some text” into it.
Using the printf command:
printf "First line of text\nSecond line of text\n" > filename.txt
This command creates a file and writes formatted text into it.
Using text editors like vi, vim, or nano:
nano filename.txt
Follow the contents below to learn more about Vim, Nano, and Vi tools.
What is the use of echo command in Linux?
In Linux, the echo command is used to display a line of text or a string that is passed as an argument. It is commonly used in shell scripts and command-line operations for various purposes. Here are the main uses of the echo command:
Display a String: It can print a line of text or a string to the terminal.
Display Variable Values: It can display the value of environment variables or user-defined variables.
Redirect Output to a File: It can be used to write text to a file by redirecting the output.
Display Special Characters: It can display special characters by using escape sequences.
Examples:
To display a simple string:
echo "Hello, World!"
To display the value of a variable:
name="John"
echo "Hello, $name!"
To write text to a file:
echo "This is a line of text" > file.txt
To append text to a file:
echo "This is another line of text" >> file.txt
To display special characters:
echo -e "Line 1\nLine 2\nLine 3"
In this example, -e enables interpretation of backslash escapes, and \n represents a newline character.
What is the use of cat command in Linux?
In Linux, the cat command is used primarily to concatenate and display the contents of files. Its main uses include:
1. Concatenate Files: It can combine multiple files and output them as a single stream of data.
2. Display File Contents: It can display the contents of a file directly to the terminal.
3. Create New Files: It can create new files by redirecting its output to a new file.
For example, to display the contents of a file named example.txt, you would use:
cat example.txt
To concatenate multiple files and display them:
cat file1.txt file2.txt
To create a new file or overwrite an existing one:
cat > newfile.txt
After typing this command, anything you type will be written to newfile.txt until you exit with Ctrl+D.
Explain vim command in Linux?
The vim command in Linux opens the Vim (Vi IMproved) text editor, which is an enhanced version of the classic vi editor. Vim is known for its efficiency and powerful features, making it a popular choice among developers and system administrators. Here’s an overview of Vim, its features, and basic usage.
Key Features of Vim
Modes: Vim operates in several modes: Normal Mode, Insert Mode, Visual Mode, Command Mode
Navigation: Allows users to navigate through text efficiently using keyboard commands.
Syntax Highlighting: Provides syntax highlighting for many programming languages.
Extensibility: Highly customizable with plugins and configuration files.
Search and Replace: Powerful search and replace capabilities.
Basic Usage
To open a file with Vim:
vim filename
If filename does not exist, Vim will create a new file with that name.
Modes in Vim
Normal Mode
Default mode when Vim starts. You can navigate and perform text operations but cannot insert text directly. In the normal mode below keys has the effect upon pressing.
Arrow keys or h, j, k, l - Move left, down, up, and right respectively.
0 - Move to the beginning of the line.
$ - Move to the end of the line.
gg - Move to the beginning of the file.
G - Move to the end of the file.
w - Move to the next word.
b - Move to the previous word.
i – vim goes to Insert Mode.
x - Delete the character under the cursor and vim goes to command mode, allows you to execute commands like save, quit, search, etc.
dd - Delete the current line. To save or cancel updated content after deleting you should go to command mode to execute commands like save, quit, search, etc.
yy - copy the current line to vim’s clipboard
yw - copy the word to vim’s clipboard
Nyy – replace the N with number of line you want, it will copy those many lines to vim’s clipboard. For example, 5yy will copy 5 lines, 2yy will copy 2 lines.
:start,end y – copy range of lines, replace start and end to the start and end line numbers. For example, :2,5y copies lines 2 through 5 to vim’s clipboard.
Y) - copy the sentence to vim’s clipboard
Y} - copy the sentence to vim’s clipboard
p – paste the contents in vim’s clipboard to the cursor position. To save or cancel pasted content you should go to command mode to execute commands like save, quit, search, etc.
There is no option to go to end of the contents, only way is pressing end key if you have option in your keyboard.
Insert Mode:
When you are in normal mode press i to go to insert mode where you can edit the text contents. After making the changes, press Esc to go to normal mode. Now you can save, cancel, undo your changes.
In Vim, undoing changes made in Insert Mode requires switching back to Normal Mode, as undo functionality is not available while in Insert Mode. Here’s how you can undo changes:
Switch to Normal Mode: If you're currently in Insert Mode, press Esc to switch back to Normal Mode.
Undo Last Change: Press u to undo the last change. Each time you press u, Vim will undo one change at a time.
Redo Changes: If you accidentally undo too much, you can redo changes by pressing Ctrl+r.
Command Mode
Accessed from Normal Mode by typing : Allows you to execute commands like save, quit, search, etc.
:w - Save the file.
:q - Quit Vim.
:wq or :x - Save and quit.
:q! - Quit without saving.
:s/old/new/g - Replace all occurrences of old with new in the current line.
:%s/old/new/g - Replace all occurrences in the entire file.
Visual Mode
Press v to enter Visual Mode for entering visual mode. You should be in Normal mode to go to Visual Mode. You cannot go to Visual mode from any other mode. Visual mode can be used for searching text, selecting and manipulating text.
How do you search in Visual mode of vim?
Use / followed by the search term to search forward. For example, to search for the word "example":
/example
Press n to move to the next occurrence and N to move to the previous occurrence.
How do you select and manipulate text in Visual mode of vim?
Modes of Visual Mode
Character-wise Visual Mode:
Enter: Press v in Normal Mode.
Usage: Allows you to select text character by character.
Example: Move the cursor to the beginning of the text you want to select, press v, and then use the arrow keys or h, j, k, l to extend the selection.
Line-wise Visual Mode:
Enter: Press V (uppercase v) in Normal Mode.
Usage: Selects entire lines. Each press of V will select the entire line where the cursor is located.
Example: Press V to start selecting the entire line, and use the arrow keys or j and k to extend the selection to additional lines.
Block-wise Visual Mode:
Enter: Press Ctrl+v in Normal Mode.
Usage: Allows you to select a rectangular block of text (also known as block visual mode). This is useful for selecting columns of text.
Example: Press Ctrl+v to start block selection, then use arrow keys or h, j, k, l to select a rectangular block of text.
Common Operations in Visual Mode
Copy (Yank): After selecting text in Visual Mode, press y to copy the selected text to the clipboard.
Cut: Press d to cut the selected text.
Paste: Move the cursor to the desired location and press p to paste the text after the cursor or P to paste it before the cursor.
Replace: After selecting text, type to replace the selected text with new content.
Delete: Press d to delete the selected text.
Indent/Unindent: Press > to indent and < to unindent the selected text.
How do you search for a file/folder in Linux?
To find all files and folders with a specific name (e.g., starting with “foo”), in the current directory and its subdirectories:
find . -name "foo*"
If you want a case-insensitive search, use the -iname flag:
find . -iname "foo*"
To find only files with a specific name (e.g., starting with “foo”), run:
find . -name "foo*" -type f
To find only directories with a specific name (e.g., starting with “foo”), run:
find . -name "foo*" -type d
To find files and directories within a directory hierarchy
find path/to/directory/ -name "fileOrDirectoryName"
NOTE: path/to/directory/ does not start with forward slash and ends with forward slash
To find files and directories within a directory hierarchy with case-insensitive search
find path/to/directory/ -iname "fileOrDirectoryName"
NOTE: path/to/directory/ does not start with forward slash and ends with forward slash
To find all files and folders with a specific name (e.g., starting with “foo”), in the home directory and its subdirectories:
find ~ -name "foo*"
How do you search a String in a text file in Linux?
To search for a string (let’s call it “searchstring”) in a text file (let’s say “myfile.txt”), you can run:
grep "searchstring" myfile.txt
To search for a string recursively in a Directory
grep -r "searchstring" path/to/directory/
NOTE: path/to/directory/ does not start with forward slash and ends with forward slash
To search for a string recursively in the current directory and its subdirectories:
grep -r "searchstring" .
To search for a string recursively in the home directory and its subdirectories:
grep -r "searchstring" ~
Options with grep:
You can use additional options with grep to modify its behaviour:
-i Ignore case (search regardless of uppercase or lowercase).
-n Show line numbers along with matching lines.
-r or -R Recursively search directories.
-l Only display filenames containing the string (useful when searching multiple files).
-o Display only matching part of the line
-w Search of whole word
-C Show Context Lines
grep -C 3 "search_string" filename.txt
This will show 3 lines of context around each match.
--color Using grep with color highlighting
grep -r "crow" . -n –-color
Combining with Other Commands
You can combine grep with other commands using pipes to filter output. For example, to list all processes containing "ssh" and then search for a specific user:
ps aux | grep ssh | grep username
How do you switch to root user in Linux?
Using sudo Command
If your user has sudo privileges, you can switch to the root user with:
sudo su
You will be prompted to enter your user password.
Using sudo -i Command
Another way to switch to the root user is by starting a root shell session:
sudo -i
Using su Command
If you know the root password, you can switch to the root user with:
su -
You will be prompted to enter the root password.
How do you grant permissions to a user in Linux using chown?
The chown command in Linux is used to change the ownership of files and directories. While chown itself doesn’t directly grant permissions, it changes the owner and group of a file or directory, which can affect permissions. Here’s how you can use it:
Basic Syntax
The basic syntax for chown is:
chown [OPTIONS] USER[:GROUP] FILE
Changing the Owner
To change the owner of a file:
chown newowner filename
Changing the Owner and Group
To change both the owner and the group of a file:
chown newowner:newgroup filename
Recursive Change
To change the owner and group of a directory and all its contents recursively:
chown -R newowner:newgroup directoryname
How do you install a software in Linux?
Most Linux distributions come with a package manager that simplifies software installation.
Debian-based Systems (e.g., Ubuntu, Debian)
sudo apt update
sudo apt install package_name
Red Hat-based Systems (e.g., Fedora, CentOS)
sudo dnf install package_name
Arch-based Systems (e.g., Arch Linux, Manjaro)
sudo pacman -S package_name
What is sudo in Linux?
In Linux, sudo stands for "superuser do." It's a command that allows a permitted user to execute a command as the superuser (root) or another user, as specified by the security policy in the /etc/sudoers file.
Here's a basic rundown of how it works:
Elevated Privileges: sudo temporarily elevates your permissions to execute a command with root privileges, which is often necessary for system administration tasks like installing software, modifying system files, or managing users.
Security: By using sudo, you don't need to log in as the root user directly. This helps maintain security by reducing the risk of accidental system-wide changes and limiting the time root privileges are active.
Audit Trails: sudo logs all commands executed, which can be useful for tracking and auditing purposes.
Configuration: The behavior of sudo is controlled by the /etc/sudoers file. You can configure which users have permission to run specific commands as root or another user, and under what conditions.
Basic Usage:
sudo command
To execute a command as a different user:
sudo -u username command
For example, to run a command as the user manu:
sudo -u manu command
All Chapters