01.1 – Access a shell prompt and issue commands with correct syntax
1. What is a Shell?
A shell is a command-line interpreter that provides a user interface for the Linux operating system. It allows users to execute commands, run scripts, and manage system resources.
Popular shells include:
- Bash (Bourne Again Shell) – Default shell in most Linux distributions.
- Zsh (Z Shell) – Advanced shell with scripting and customization capabilities.
- Fish (Friendly Interactive Shell) – Focuses on usability.
2. Accessing a Shell Prompt
Methods to Access a Shell:
- From a Physical Console:
- On a physical system, access the shell via the terminal (Ctrl + Alt + F2 through Ctrl + Alt + F6 for TTY sessions).
- Via SSH (Secure Shell):
- Remotely access a Linux machine:
ssh username@hostname_or_ipExample:
ssh root@192.168.1.10- Graphical Terminal Emulator:
- On desktop environments, open a terminal emulator (e.g., GNOME Terminal, Konsole). Example:
- Shortcut: Ctrl + Alt + T (on many systems).
- On desktop environments, open a terminal emulator (e.g., GNOME Terminal, Konsole). Example:
3. Basic Shell Prompt Anatomy
A typical shell prompt looks like:
[username@hostname current_directory]$Example:
[root@localhost ~]#- username: The user logged into the shell.
- hostname: The name of the machine.
- current_directory: The present working directory (~ represents the user’s home directory).
- $: Non-root user prompt.
- #: Root user prompt.
4. Syntax of Shell Commands
The general syntax of a shell command is:
command [option(s)] [argument(s)]- command: The executable program or built-in shell command.
- option(s): Modifiers that alter the behavior of the command.
- argument(s): Targets or inputs for the command.
cd – (change directory)
Go to specified directory
cd [path/to/directory]
Go up to the parent directory of the current directory
cd ..
Go to the home directory of the current user
cd
Go to the home directory of specified user
cd ~/[username]
Go to the previously chosen directory
cd -
Go to the root directory
cd /
ls – (list contents of a directory)
List files one per line
ls -l
List all files, including hidden files
ls -a
List all files, with trailing / added to directory name
ls -F
Long format list (permissions, ownership, size, and modification date) of all files
ls -la
Long format list with size displayed using human-redable units (KiB, MiB, GiB)
ls -lh
Long format list sorted by size (decending)
ls -lS
Long format list of all files, sorted by modification date (oldest first)
ls -ltr
Only list directories
ls -d */
pwd – (display present working directory)
Print the current directory
pwd
Print the current directory, and resolve all symlinks (i.e. show the “physical” path)
pwd -P
date – (displays the current date)
Display the current date using the default locale’s format
date +%c
Display the current date in UTC, using the ISO 8601 format
date -u +%Y-%m-%dT%H:%M:%S%Z
Display the current date as Unix timestamp (seconds since the Unix epoch)
date +%s
Convert a date specified as a Unix timestamp to the default format
date -d @[1473305798]
Convert a given date to Unix timestamp format
date -d "[2018-09-01 00:00]" +%s --utc
Display the current date using the RFC-3339 format (YYYY-MM-DD hh:mm:ss TZ)
date --rfc-3339=s
Set the current date using the format MMDDhhmmYYYY.ss (YYYY and .ss are optional)
date [093023592021.59]
Display the current ISO week number
date +%V
hostname – (display computer’s hostname)
Show current host name
hostname
Show the network address of the host name
hostname -i
Show all network address of the host
hostname -I
Show the FQDN (Fully Qualified Domain Name)
hostname --fqdn
Set current host name
hostname [new_hostname]
id – (display user’s identity information)
Display current user’s ID (UID), group ID (GID) and group to which they belong
id
Display the current user identity as a number
id -u
Dislpay the current group identity as a number
id -g
Display an arbitrary user’s ID (UID), group ID (GID) and group to which they belong
id [username]
echo – (echo argument to output)
Print a text message. Note: Qoute are optional
echo "[Hello World]"
Print a message with environment variables
echo "[My path is $PATH]"
Print a message without the trailing newline
echo -n "[Hello World]"
Append a message to the file
echo "[Hello World]" >> [file.txt]
Enable interpretation of backlash escapes (special characters)
echo -e "[Column 1\tColumn 2]"
print the exit status of the last executed command (Note: In windows Command prompt and PowerShell the equivalent commands are echo %errorlevel% and $lastexitcode respectively)
echo $?
locate – (locate file or directory within file system using the locate database)
Look for pattern in the database. Note: the database is recomputed periodically (usually weekly or daily)
locate [pattern]
Look for a file by is=ts exact filename (a pattern containing no globbing characters is interpreted as pattern)
locate '*/[filename]'
Recomputed the database. You need to do it if you want to find recently added files
sudo updatedb
updatedb – (update the database used by the locate command)
Refresh database content
sudo updatedb
Display file names as soon as they are found
sudo updatedb --verbose
head – (print first ten lines of a file to output)
Output the first few lines of a file
head -n [count] [path/to/file]
tail – (print the last ten lines of a file to output)
Show last ‘count’ lines in file
tail --lines [count] [path/to/file]
Print a file from a specific line number
tail --lines +[count] [path/to/file]
Print a specific count of bytes from the end of a given file
tail --bytes [count] [path/to/file]
Print the last lines of a given file and keep reding file until Ctrl + C
tail --follow [path/to/file]
Keep reding file until Ctrl + C, even if the file is inaccessible
tail --retry --follow [path/to/file]
Show last ‘num’ lines in ‘file’ and refresh every ‘n’ seconds
tail --lines [count] --sleep-interval [seconds] --follow [path/to/file]
alias – (display aliases configured for user)
List all aliases
alias
Create a generic alias
alias [word]="[command]"
View the command associated to a given alias
alias [word]
Remove an aliased command
unalias [word]
Turn rm into an interactive command
alias [rm]="[rm --interactive]"
Create la as a shortcut for ls -all
alias [la]="[ls --all]"
01.2 – Use input-output redirection (>, >>, |, 2>, etc.)
following link helps to understand the concept of redirections
https://www.redhat.com/en/blog/linux-shell-redirection-pipelining

1. Basic Redirection Operators
| Operator | Purpose | Description |
| > | Redirect standard output | Overwrites the target file with the output. |
| >> | Append standard output | Appends the output to the target file instead of overwriting. |
| 2> | Redirect standard error | Sends error messages to a file. |
| 2>> | Append standard error | Appends error messages to a file. |
| ` | ` | Pipe output to another command |
| < | Redirect standard input | Reads input from a file instead of the keyboard. |
| &> | Redirect both stdout and stderr | Combines stdout and stderr to a single destination (overwrite). |
| &>> | Append both stdout and stderr | Combines stdout and stderr to a single destination (append). |
Redirection with >
command > file: Sends standard output to<file>command 2> file: Sends error output to<file>command 2>&1: Sends error output to standard outputcommand > file 2>&1: Sends standard output and the error output to a filecommand &> file: Sends standard output and the error output to a filecommand 2>&1 > file: Sends error output to standard input and the standard input to a file
Append with >>
command >> file: Appends standard output to a filecommand 2>> file: Appends error output to a filecommand >> file 2>&1: Appends standard output and error output to a filecommand &>> file: Appends standard output and error output to a filecommand 2>&1 >> file: Sends error output to standard input and appends standard input to a file
Redirect with <
command < input: Feeds a command input from<input>command << input: Feeds a command or interactive program with a list defined by a delimiter; this is known as a here-document (heredoc)command <<< input: Feeds a command with<input>; this is known as a here-string

command1 | command2 | command32. Examples and Details
2.1 Redirecting Standard Output (>)
Redirects the output of a command to a file, overwriting its content.
echo "Hello, World!" > output.txt- Description: Writes “Hello, World!” to output.txt.
- Result: If output.txt exists, it is overwritten.
2.2 Appending Standard Output (>>)
Appends the output of a command to the end of a file.
echo "Appending text" >> output.txt- Description: Adds “Appending text” to the end of output.txt.
- Result: Preserves existing content in the file.
2.3 Redirecting Standard Error (2>)
Redirects error messages to a file.
ls nonexistentfile 2> error.log- Description: Redirects the error message from the ls command to error.log.
2.4 Appending Standard Error (2>>)
Appends error messages to the end of a file.
ls nonexistentfile 2>> error.log- Description: Adds the error message to error.log without overwriting its content.
2.5 Redirecting Both Standard Output and Standard Error (&> and &>>)
Redirects both the output and error streams.
- Overwrite both stdout and stderr:
ls existingfile nonexistentfile &> combined.log- Append both stdout and stderr:
ls existingfile nonexistentfile &>> combined.log2.6 Using Pipes (|)
Passes the output of one command as input to another.
ls -l | grep "txt"- Description: Lists files and filters those containing “txt”.
2.7 Redirecting Input (<)
Reads input from a file instead of the keyboard.
cat < input.txt- Description: Displays the content of input.txt.
3. Combining Redirections
3.1 Redirecting Output and Errors Separately
You can redirect stdout and stderr to different files.
command > output.log 2> error.log3.2 Merging stdout and stderr
To combine and redirect both streams:
command > combined.log 2>&1- Description: Sends both stdout and stderr to combined.log.
4. Real-Life Use Cases
4.1 Logging Output and Errors
backup_script.sh > backup.log 2>> backup_errors.log- Description: Logs successful output to backup.log and appends errors to backup_errors.log.
4.2 Using Pipes with Filters
grep "error" /var/log/syslog | tee errors_found.log- Description: Searches for “error” in /var/log/syslog and saves the results to errors_found.log while displaying them on the terminal.
4.3 Redirecting Input and Output Together
sort < unsorted.txt > sorted.txt- Description: Sorts the content of unsorted.txt and saves it to sorted.txt.
5. Special Notes
- Avoid Overwriting: Use >> to prevent accidental overwrites.
- Use tee: For simultaneous display and saving to a file.
- Order Matters: Ensure correct ordering when combining redirections.
- Check File Permissions: Ensure proper write permissions for redirection targets.
01.3 – Use grep and regular expressions to analyze text
The grep command is a powerful text search tool used to match patterns in files or input streams. It supports basic and extended regular expressions to filter and analyze text effectively. Below is a comprehensive guide with examples:
1. Basic Syntax
grep [options] PATTERN [FILE...]- PATTERN: The search pattern (can include text or a regular expression).
- FILE: The file(s) to search in. If omitted, grep reads from standard input.
- options: Flags to modify the behavior of grep.
2. Common Options
| Option | Description |
| -i | Case-insensitive search. |
| -v | Invert the match (show lines that don’t match). |
| -c | Count the number of matching lines. |
| -n | Show line numbers for matches. |
| -r or -R | Recursive search in directories. |
| -l | List file names with matches. |
| -E | Use extended regular expressions (ERE). |
3. Examples
3.1. Searching for a Word
grep "root" /etc/passwd- Matches lines containing the word root in /etc/passwd.
3.2. Case-Insensitive Search
grep -i "root" /etc/passwd- Matches root, Root, ROOT, etc.
3.3. Display Line Numbers
grep -n "" /etc/passwd- Shows lines containing with their line numbers.
3.4. Count Matching Lines
grep -c "nologin" /etc/passwdgrep -c "nologin" /etc/passwd- Displays the count of lines containing nologin.
3.5. Invert Match
grep -v "nologin" /etc/passwd- Displays lines not containing nologin.
3.6. Recursive Search
grep -r "error" /var/log/- Searches for error recursively in the /var/log directory.
3.7. List File Names
grep -l "error" /var/log/*- Lists files in /var/log that contain the word error.
4. Regular Expressions (Basic vs. Extended)
4.1. Basic Regular Expressions (BRE)
| Pattern | Meaning |
| ^abc | Lines starting with abc. |
| abc$ | Lines ending with abc. |
| a.b | Matches a followed by any character and b. |
| a* | Matches zero or more occurrences of a. |
| [abc] | Matches any one of a, b, or c. |
| [^abc] | Matches any character except a, b, or c. |
| a\{2\} | Matches exactly 2 occurrences of a. |
4.2. Extended Regular Expressions (ERE)
To enable ERE, use the -E option or egrep command.
| Pattern | Meaning |
| a+ | Matches one or more occurrences of a. |
| a{2,} | Matches 2 or more occurrences of a. |
| `a | b` |
| (abc) | Matches the sequence abc. |
5. Examples of Regular Expressions
5.1. Lines Starting with a Pattern
grep "^root" /etc/passwd- Matches lines starting with root.
5.2. Lines Ending with a Pattern
grep "$" /etc/passwd- Matches lines ending with .
5.3. Matching Any Single Character
grep "r..t" /etc/passwd- Matches root, raxt, etc.
5.4. Matching Zero or More Occurrences
grep "ba*" /etc/passwd- Matches b, ba, baa, etc.
5.5. Use of Extended Regular Expressions
grep -E "root|nologin" /etc/passwd- Matches lines containing either root or nologin.
5.6. Counting Lines Matching a Pattern
grep -c "^$" myfile.txt- Counts the number of empty lines in myfile.txt.
5.7. Find Words with Specific Length
grep -E "\b[a-zA-Z]{5}\b" myfile.txt- Matches words with exactly 5 characters.
6. Combining Multiple Commands
6.1. Searching with grep and Piping
cat /var/log/messages | grep "error" | grep -v "ignored"- Searches for error in /var/log/messages and excludes lines containing ignored.
6.2. Using grep with Other Commands
ps aux | grep "httpd"- Filters processes for httpd.
7. Real-Life Examples
7.1. Check for Open Ports
netstat -tuln | grep ":80"- Finds processes listening on port 80.
7.2. Analyze Logs for Errors
grep -i "error" /var/log/httpd/access_log- Searches for error in web server logs.
7.3. Find User Information
grep "^user1" /etc/passwd- Finds the user1 entry in /etc/passwd.
Practice Exercises
- Find lines in /etc/passwd starting with a.
- Count the number of lines in /var/log/messages containing failed.
- Search for lines with ssh or telnet in a file.
By mastering grep and regular expressions, you can efficiently analyze text files and logs, a crucial skill for system administrators preparing for the RHCSA exam.
Following are reference
https://www.redhat.com/en/blog/regex-grep-data-flow
https://www.redhat.com/en/blog/how-to-use-grep
Search for a pattern with a file
grep "[search_pattern]" [path/to/file]
Search for an exact string (disables regular expressions)
grep --fixed-strings "[exact_string]" [path/to/file]
Search for a pattern in all files recursively in a directory, showing line number of matches, ignoring binary files
grep --recursive --line-number --binary-files=[without-match] "[search_pattern]" [path/to/file]
Use extended regular expressions (supports ?, +, {}, () and |), in case-insensitive mode
grep --extended-regexp --ignore-case "[search_pattern]" [path/to/file]
Print 3 lines of context around, before, or after each match
grep --[context|before-context|after-context]=[3] "[search_pattern]" [path/to/file]
Print file name and line number for each match with color output
grep --with-filename --line-number --color=always "[search_pattern]" [path/to/file]
Search for lines matching a pattern, printing only the matched text
grep --only-matching "[search_pattern]" [path/to/file]
search stdin for lines that do not match a pattern
cat [path/to/file] | grep --invert-match "[serach_pattern]"
01.4 – Access remote systems using SSH
Secure Shell (SSH) is a protocol used to securely access and manage remote systems over a network. SSH provides encrypted communication, ensuring the confidentiality and integrity of data.
1. Installing SSH
Before accessing remote systems, ensure that the SSH service is installed and running on both the client and server.
Command to install SSH (on most distributions):
# Install SSH server (on the remote system)
sudo yum install -y openssh-server# Install SSH client (on the local system, if not already installed)
sudo yum install -y openssh-clients2. Starting and Enabling the SSH Service
To allow remote access, the SSH daemon (sshd) must be running on the server.
Commands:
# Start the SSH service
sudo systemctl start sshd# Enable SSH to start at boot
sudo systemctl enable sshd# Check the status of the SSH service
sudo systemctl status sshd3. Accessing a Remote System Using SSH
To connect to a remote system using SSH, use the ssh command followed by the username and IP address (or hostname) of the remote system.
Syntax:
ssh username@remote_hostExample:
ssh root@192.168.1.1004. Changing the Default SSH Port
By default, SSH runs on port 22. For security, you can change this to a custom port.
Steps:
- Edit the SSH configuration file:
sudo vi /etc/ssh/sshd_config- Locate the line starting with
#Port 22and change it to a custom port (e.g.,Port 2222). Remove the#to uncomment the line:
Port 2222- Restart the SSH service:
sudo systemctl restart sshdConnecting with a Custom Port:
Use the -p option to specify the port.
ssh -p 2222 root@192.168.1.1005. Generating and Using SSH Keys
Using SSH keys enhances security by replacing password authentication with public-key authentication.
Steps to Generate SSH Keys:
- Generate an SSH key pair on the client system:
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa- Copy the public key to the remote server:
ssh-copy-id username@remote_hostConnect Without Password:
Once the public key is copied, you can log in without a password:
ssh username@remote_host6. SSH Configuration for Automation
You can configure SSH settings for convenience in the ~/.ssh/config file on the client system.
Example Configuration:
Host remote_server
HostName 192.168.1.100
User root
Port 2222Connecting with Short Name:
ssh remote_server7. Secure SSH Configuration (Best Practices)
- Disable root login: Edit
/etc/ssh/sshd_configand set:
plaintext
PermitRootLogin noRestart the SSH service:
sudo systemctl restart sshd- Allow specific users: Add the following to
/etc/ssh/sshd_config:
plaintext
AllowUsers user1 user2- Use strong authentication methods: Set
PasswordAuthentication noin/etc/ssh/sshd_configto enforce key-based authentication. - Limit failed login attempts: Use a tool like
fail2banto block IPs after repeated failed login attempts:
sudo yum install -y fail2ban8. Troubleshooting SSH
- Check Connectivity:
ping remote_host- Test SSH Connection Verbosely:
ssh -v username@remote_host- Check SSH Logs: On the server:
sudo tail -f /var/log/secureExample Scenarios
- Copy Files Over SSH: Use
scpto securely copy files:
scp /path/to/local/file user@remote_host:/path/to/destination- Execute Commands Remotely: Run a single command on the remote system:
ssh username@remote_host - Use SSH Tunneling: Forward local port 8080 to remote port 80:
ssh -L 8080:localhost:80 user@remote_hostThese steps and best practices ensure a secure and efficient SSH setup, which is vital for accessing and managing remote systems.
REF : – https://www.redhat.com/en/blog/access-remote-systems-ssh
SSH example
SSH server installation (server_A)
sudo dnf install openssh-server
systemctl enable --now sshdSSH client installation (server_B)
dnf install -y openssh-clientsLogin SSH
Configure key based authentication via SSH
create keys for the client machine (server_B)
ssh-keygenGenerating public/private rsa key pair.
Enter file in which to save the key (/home/tim/.ssh/id_rsa):
Created directory '/home/tim/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/tim/.ssh/id_rsa
Your public key has been saved in /home/tim/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:5xDIXKLZi3p17L7SQOnv4NzVqfr0m98wwwVgYlovKio tim@d11
The key's randomart image is:
+---[RSA 3072]----+
| . . + o |
| * + + + . |
| o =.o . . . |
| .oo o . . |
| .o+ S . .|
| . oo+ + . o . |
| E o .+. + o = |
| o o.+oo o . = |
| oo*+o +o. .|
+----[SHA256]-----+hidden file “.ssh” is created in the user home directory
| file | name |
|---|---|
| id_rsa | private key (do not share) |
| id_rsa.pub | public key that can be shared |
ssh-copy-id user@server_A
now you can disable password-based login from “server_A” and start key-based passwordless login to the remote server machine
01.5 – Log in and switch users in multiuser targets
| Feature | SysV init Runlevel | systemd Target | Example Commands |
|---|
| Definition | Runlevels define the state of the system. | Targets define states or groups of services. | N/A |
| Management Tool | /etc/inittab | systemctl | N/A |
| Default State Configuration | Edit /etc/inittab file. | Use systemctl set-default. | SysV: Edit /etc/inittab to set id:3:initdefault:systemd: systemctl set-default multi-user.target |
| State Change Command | init <runlevel> | systemctl isolate <target> | SysV: init 3systemd: systemctl isolate multi-user.target |
| Runlevels/Targets Description | Numerical identifiers (0-6). | Named targets (descriptive names). | N/A |
| Example States | – 0: Halt | – poweroff.target: Halt | SysV: init 0systemd: systemctl isolate poweroff.target |
– 1: Single-user mode | – rescue.target: Single-user mode | SysV: init 1systemd: systemctl isolate rescue.target |
– 3: Multi-user mode | – multi-user.target: Multi-user mode (no GUI) | SysV: init 3systemd: systemctl isolate multi-user.target |
– 5: Multi-user + GUI | – graphical.target: Multi-user + GUI | SysV: init 5systemd: systemctl isolate graphical.target |
– 6: Reboot | – reboot.target: Reboot | SysV: init 6systemd: systemctl isolate reboot.target |
| Enable/Disable Services | Use /etc/rc.d or /etc/init.d scripts. | Use systemctl enable/disable. | SysV: chkconfig httpd onsystemd: systemctl enable httpd |
| Parallel Startup | No, runs scripts sequentially. | Yes, supports parallel service startup. | N/A |
| Service Monitoring | Limited; no built-in monitoring. | Built-in service management and monitoring. | Check service in systemd: systemctl status httpd |
Multiuser target: The default systemd target in most Linux distributions for multi-user, non-graphical environments (similar to runlevel 3 in SysV init systems).Command to check the current target:
systemctl get-defaultCommand to set the default to multiuser target:
systemctl set-default multi-user.targetCommand to switch to multiuser target immediately:
sudo systemctl isolate multi-user.targetLog In to a System in Multiuser Target
Access via Virtual Console:
Use Ctrl + Alt + F2 to Ctrl + Alt + F6 to switch between virtual consoles.

Log in using your username and password.
SSH Login:
Use SSH to connect to the system in multiuser target:
ssh username@hostname_or_ipSwitch Users in Multiuser Targets
- Switch User Temporarily:
- Use the
sucommand to switch to another user without logging out:su - username - The
-option ensures the user’s environment variables and shell are loaded.
- Use the
- Switch to the Superuser (Root):
- If you have superuser privileges, use:
su - - Enter the root password when prompted.
- If you have superuser privileges, use:
- Switch with
sudo:- To execute a single command as another user:
sudo -u username command - Example:
sudo -u apache systemctl restart httpd
- To execute a single command as another user:
- Log in as a Different User:
- Use
logoutorCtrl+Dto log out of the current session. - Log in as a different user when prompted.
- Use
Best Practices for User Switching
- Avoid using the root account directly unless necessary; use
sudofor administrative tasks. - Always log out from elevated privileges when not needed to reduce security risks.
Troubleshooting Tips
Ensure the system is not in rescue or emergency mode, which limits user logins.
If you cannot log in:
Verify that the target is set correctly: systemctl list-units --type=target
Check if the user account exists: cat /etc/passwd | grep username
Reset the password if needed: sudo passwd username
01.6 – Archive, compress, unpack, and uncompress files using tar, gzip, and bzip2
1. Using tar (Tape Archive)
tar is a utility used to create archives and manipulate them. It doesn’t compress files by itself but can work with compression utilities like gzip and bzip2.
Common Tar Options
- -c: Create an archive.
- -x: Extract files from an archive.
- -v: Verbose (shows progress).
- -f: Specify the filename of the archive.
- -t: List the contents of an archive.
- -z: Use gzip for compression.
- -j: Use bzip2 for compression.
Examples with tar
- Create an Archive:
tar -cvf archive.tar file1 file2 directory/- archive.tar: Name of the archive.
- file1, file2, and directory/: Files and directories to archive.
- List Contents of an Archive:
tar -tvf archive.tar- Extract an Archive:
tar -xvf archive.tar- Create a Compressed Archive with gzip:
tar -czvf archive.tar.gz file1 file2 directory/- Extract a Compressed Archive with gzip:
tar -xzvf archive.tar.gz- Create a Compressed Archive with bzip2:
tar -cjvf archive.tar.bz2 file1 file2 directory/- Extract a Compressed Archive with bzip2:
tar -xjvf archive.tar.bz22. Using gzip and gunzip
gzip is a utility for compressing files, while gunzip is used to decompress them.
Common Options
- gzip [file]: Compress the file, replacing the original with a .gz file.
- gunzip [file.gz]: Decompress the .gz file.
- gzip -d [file.gz]: Another way to decompress the .gz file.
Examples with gzip
- Compress a File:
gzip file.txtResult: Creates file.txt.gz.
- Compress Multiple Files:
gzip file1 file2Result: Creates file1.gz and file2.gz.
- Decompress a File:
gunzip file.txt.gzResult: Restores file.txt.
- Keep the Original File While Compressing:
gzip -c file.txt > file.txt.gz3. Using bzip2 and bunzip2
bzip2 provides higher compression ratios than gzip, and bunzip2 is used to decompress .bz2 files.
Common Options
- bzip2 [file]: Compress the file, replacing the original with a .bz2 file.
- bunzip2 [file.bz2]: Decompress the .bz2 file.
- bzip2 -d [file.bz2]: Another way to decompress the .bz2 file.
Examples with bzip2
- Compress a File:
bzip2 file.txtResult: Creates file.txt.bz2.
- Compress Multiple Files:
bzip2 file1 file2Result: Creates file1.bz2 and file2.bz2.
- Decompress a File:
bunzip2 file.txt.bz2Result: Restores file.txt.
- Keep the Original File While Compressing:
bzip2 -c file.txt > file.txt.bz24. Combining Utilities
You can use tar with gzip or bzip2 for both archiving and compressing in a single step.
Examples
- Archive and Compress with gzip:
tar -czvf archive.tar.gz file1 file2 directory/- Archive and Compress with bzip2:
tar -cjvf archive.tar.bz2 file1 file2 directory/- Extract gzip Compressed Archive:
tar -xzvf archive.tar.gz- Extract bzip2 Compressed Archive:
tar -xjvf archive.tar.bz2Summary Table of Commands
| Task | Command |
| Create tar archive | tar -cvf archive.tar file1 file2 |
| Extract tar archive | tar -xvf archive.tar |
| Compress with gzip | gzip file.txt |
| Decompress gzip file | gunzip file.txt.gz |
| Compress with bzip2 | bzip2 file.txt |
| Decompress bzip2 file | bunzip2 file.txt.bz2 |
| Archive + gzip compression | tar -czvf archive.tar.gz file1 file2 |
| Archive + bzip2 compression | tar -cjvf archive.tar.bz2 file1 file2 |
| Extract tar.gz | tar -xzvf archive.tar.gz |
| Extract tar.bz2 | tar -xjvf archive.tar.bz2 |
Notes:
- Always use -v for verbosity during operations for clarity, especially in exams or production.
- Practice creating, extracting, and listing archives to become proficient with syntax.
- Be cautious with paths when extracting archives to avoid overwriting existing files.
01.7 – Create and edit text files
01.8 – Create, delete, copy, and move files and directories
touch – (touch a file to either create it with no content or update it’s last accessed time)
Create specific files
touch [path/to/file1 path/to/file2 ...]
Set the file access or modification times to the current one and don’t create file if it doesn’t exist
touch -c -[a|m] [path/to/file1 path/to/file2 ...]
set the file time to s specific value and don’t create file if it doesn’t exist
touch -c -t [YYYYMMDDHHMM.SS] [path/to/file1 path/to/file2 ...]
Set the file time of a specific file to the time of another file and don’t create file if it doesn’t exist
touch -c -r [~/.emacs] [path/to/file1 path/to/file2 ...]
mkdir – (make directory)
Create specific directories
mkdir [path/to/directory1 path/to/directory2 ...]
Create specific directories and their parents if needed
mkdir -p [path/to/directory1 path/to/directory2 ...]
Create directories with specific permissions
mkdir -m [rwxrw-r--] [path/to/directory1 path/to/directory2 ...]
rm – (remove file or empty directory)
Remove specific files
rm [path/to/file1 path/to/file2 ...]
Remove specific files ignoring nonexisting ones
rm -f [path/to/file1 path/to/file2 ...]
Remove specific files [i]nteractively prompting before each removal
rm -i [path/to/file1 path/to/file2 ...]
cp – (copy file or directory to file or directory)
Copy a file to another location
cp [path/to/]
Copy a file into another directory, keeping the filename
cp [path/to/source_file.ext] [path/to/target_parent_directory]
Recursively copy a directory’s contents ti another location (if the destination exists, the directory is copied inside it)
cp -R [path/to/source_directory] [path/to/target_directory]
Copy a directory recursively, in verbose mode (shows files as they are copied)
cp -vR [path/to/source_directory] [path/to/target_directory]
Copy multiple files at once to a directory
cp -t [path/to/destination_directory] [path/to/file1 path/to/file2 ...]
Copy text files to another location, in interactive mode (prompts user before overwriting)
cp -i [*.txt] [path/to/target_directory]
Follow symbolic links before copying
cp -L [link] [path/to/target_directory]
Use the first argument as the destination directory (useful for xargs … | cp -t )
cp -t [path/to/target_directory] [path/to/file_or_directory1 path/to/file_or_directory1 ...]
mv – (move file or directory to file or directory)
Rename a file or directory when the taget is not an existing directory
mv [path/to/source] [path/to/target]
Move a file or directory into an existing directory
mv [path/to/sorce] [path/to/existing_directory]
Move multiple files into an existing directory, keeping the filenames unchanged
mv [path/to/source1 path/to/source2 ...] [path/to/existing_directory]
Do not prompt for confirmation before overwriting existing files
mv -f [path/to/source] [path/to/target]
Prompt for confirmation before overwriting existing files, regardless of file permissions
mv -i [path/to/source] [path/to/target]
Do not overwrite existing files at the target
mv -n [path/to/source] [path/to/target]
Move files in verbose mode, showing files after they are moved
mv -v [path/to/source] [path/to/target]
01.9 – Create hard and soft links
What are Links in Linux?
- Hard Link: A direct reference to the same inode as the original file. Multiple hard links share the same data blocks, meaning changes to one link affect all others.
- Features:
- Cannot span across file systems.
- Cannot be created for directories.
- File and its hard links are indistinguishable.
- File is not deleted until all hard links are removed.
- Features:
- Soft Link (Symbolic Link): A shortcut or pointer to the file’s path. It references the file name, not the inode.
- Features:
- Can span across file systems.
- Can link to directories.
- Breaks if the target file is deleted or moved.
- Displays as a shortcut in the file system.
- Features:
Commands to Create Links
1. Create a Hard Link
ln [source_file] [hard_link]Example:
touch original.txtln original.txt hardlink.txt
- Explanation:
- ln: Command to create a hard link.
- original.txt: The source file.
- hardlink.txt: The new hard link to the source file.
Verify:
ls -liOutput:
12345 -rw-r--r-- 2 user user 0 Nov 27 10:00 hardlink.txt
12345 -rw-r--r-- 2 user user 0 Nov 27 10:00 original.txtBoth files share the same inode number (12345), indicating they are hard links.
2. Create a Soft Link (Symbolic Link)
ln -s [source_file] [soft_link]Example:
ln -s original.txt softlink.txt- Explanation:
- ln -s: Command to create a soft link.
- original.txt: The source file.
- softlink.txt: The symbolic link pointing to the source file.
Verify:
ls -lOutput:
lrwxrwxrwx 1 user user 12 Nov 27 10:00 softlink.txt -> original.txt- l at the beginning indicates a symbolic link.
- -> original.txt shows the target of the symbolic link.
Differences Between Hard and Soft Links
| Feature | Hard Link | Soft Link |
| Inode Shared | Yes | No |
| Works Across File Systems | No | Yes |
| Link to Directories | No | Yes |
| Broken if Original is Deleted | No | Yes |
Practical Examples
1. Demonstrating Hard Links
- Create a file and add content:
echo "Hello, RHCSA!" > original.txt- Create a hard link:
ln original.txt hardlink.txt- Modify the content via the hard link:
echo "Adding more content" >> hardlink.txt- Verify both files:
cat original.txt
cat hardlink.txtOutput:
Hello, RHCSA!
Adding more content2. Demonstrating Soft Links
- Create a symbolic link:
ln -s original.txt softlink.txt- View the link:
ls -l- Delete the source file:
rm original.txt- Access the soft link:
cat softlink.txtOutput:
cat: softlink.txt: No such file or directoryImportant Notes for RHCSA Exam
- Use ln for hard links and ln -s for soft links.
- Know the limitations of hard links (e.g., cannot cross file systems or link directories).
- Understand the ls -l output to distinguish hard and soft links.
- Deleting a hard link doesn’t affect the original file, but deleting a soft link’s target breaks the link.
01.10 – List, set, and change standard ugo/rwx permissions
1. Listing Permissions
To view the permissions of files and directories, use the ls -l command.
Syntax:
ls -l [file/directory]Example:
$ ls -l-rw-r--r-- 1 user group 1024 Nov 27 09:00 file.txtExplanation:
-rw-r--r--: Permissions-indicates it’s a file (not a directory).rw-(user): The owner can read and write.r--(group): Members of the group can only read.r--(others): Others can only read.
1: Hard link count.user: Owner of the file.group: Group associated with the file.1024: File size in bytes.Nov 27 09:00: Last modification date and time.file.txt: File name.
2. Setting Permissions
Use the chmod command to set permissions. Permissions can be changed using symbolic or numeric modes.
a. Using Symbolic Mode
In symbolic mode, specify the class (u, g, o) and the operation (+, -, =) to modify permissions.
Syntax:
chmod [class][operation][permissions] file- Class:
u: Userg: Groupo: Othersa: All (u, g, and o)- Operation:
+: Add permission-: Remove permission=: Set exact permission
Examples:
- Add execute permission for the user:
chmod u+x file.txt- Remove write permission for others:
chmod o-w file.txt- Set read-only for all:
chmod a=r file.txtb. Using Numeric (Octal) Mode
In numeric mode, permissions are represented as a three-digit number (owner, group, others).
- Permission Values:
4: Read (r)2: Write (w)1: Execute (x)0: No permission
Combine values to set permissions:
7(4+2+1): Read, write, execute6(4+2): Read, write5(4+1): Read, execute4: Read only
Syntax:
chmod [numeric_permissions] fileExamples:
- Grant read, write, and execute to the owner; read and execute to group and others:
chmod 755 file.txt- Grant read and write to all:
chmod 666 file.txt- Remove all permissions:
chmod 000 file.txt3. Changing Ownership and Group
Use the chown command to change ownership and the chgrp command to change the group.
a. Changing Ownership
Syntax:
chown [user] fileExample:
chown john file.txtb. Changing Group
Syntax:
chgrp [group] fileExample:
chgrp developers file.txtc. Changing Ownership and Group Simultaneously
Syntax:
chown [user]:[group] fileExample:
chown john:developers file.txt4. Recursive Permission Changes
Use the -R option with chmod, chown, or chgrp to apply changes recursively to directories and their contents.
Example:
- Apply
755to all files and directories recursively:
chmod -R 755 /path/to/directory- Change ownership recursively:
chown -R john:developers /path/to/directory5. Special Notes
- Default Permissions: Use the
umaskcommand to set default permissions for new files and directories. - View Effective Permissions: Use
getfaclto view detailed permissions, including ACLs (Access Control Lists). - Testing Permissions: Use the
suorsudo -ucommands to test file access for different users.
01.11 – Locate, read, and use system documentation including man, info, and files in /usr/share/doc
System Documentation Overview
Linux systems come with various sources of documentation to help users understand commands, configuration files, and system behavior. These include:
- man (Manual Pages): Concise, sectioned reference for commands and system components.
- info: More detailed, often hyperlinked, documentation for GNU utilities.
- Files in /usr/share/doc: Supplemental documentation, including README files, example configurations, and license details for installed packages.
1. Using man (Manual Pages)
Command Syntax
man [section] command_or_topic- section: The manual is divided into numbered sections. Some common sections:
- 1: User commands
- 5: File formats
- 8: System administration commands
- If no section is specified, man searches all sections in order.
Examples
- Basic Usage
man lsDisplays the manual page for the ls command.
- Search in a Specific Section
man 5 passwdDisplays information about the /etc/passwd file format (from section 5).
- Search for a Keyword
man -k fileLists all manual pages related to “file”. Equivalent to:
apropos file- View All Matching Pages If multiple commands share a name, use -a:
man -a printfView pages for both the shell built-in and library function.
Navigating in man
- Scroll: Arrow keys or Page Up/Page Down
- Search: /keyword then press n for next match or N for previous.
- Quit: Press q.
2. Using info
Command Syntax
info [topic]Examples
- View Documentation for a Command
info lsOpens a detailed document for the ls command, often more expansive than man.
- Search in info
- Press Ctrl+S to search for a keyword.
- Use n to jump to the next match.
- Navigate info
- Use arrow keys or Tab to move between links.
- Press Enter to follow a link.
- Press u to go up one level.
- List Available Topics
info coreutilsDisplays an index of all commands in the coreutils package.
3. Reading Files in /usr/share/doc
Overview
- The /usr/share/doc directory contains documentation for installed packages.
- Common files include:
- README: Overview or special notes for the package.
- LICENSE: Licensing details.
- Examples: Sample configuration files or scripts.
- Changelog: Version history.
Exploring the Directory
- List Contents
ls /usr/share/docDisplays directories for each installed package.
- View Files for a Specific Package
ls /usr/share/doc/httpdLists files related to the httpd (Apache) package.
- Read a File
cat /usr/share/doc/httpd/README- Search for Documentation
find /usr/share/doc -type f -iname "*example*"Finds files with “example” in their name.
Best Practices for System Documentation
- Start with man: Use it for quick reference and syntax details.
- Refer to info: When deeper details or examples are needed for GNU utilities.
- Check /usr/share/doc: For package-specific details, configuration samples, and troubleshooting tips.
Quick Example: Understanding sshd Configuration
- View the man Page
man sshd_configLearn about directives in the /etc/ssh/sshd_config file.
- Search for an Option
/PermitRootLogin
Locate the section on PermitRootLogin.
- Check /usr/share/doc
ls /usr/share/doc/opensshcat /usr/share/doc/openssh/READMELook for additional examples or details about the OpenSSH server.
Tips for RHCSA Exam
- Practice Navigation:
- Be comfortable with man and info for commonly used commands.
- Explore /usr/share/doc:
- Familiarize yourself with the type of files stored for key packages.
- Time Management:
- Use search efficiently (/keyword in man or Ctrl+S in info) during the exam.
Discover more from Altgr Blog
Subscribe to get the latest posts sent to your email.
