[RHCSA] 01 – Understand and use essential tools

    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:

    1. From a Physical Console:
      • On a physical system, access the shell via the terminal (Ctrl + Alt + F2 through Ctrl + Alt + F6 for TTY sessions).
    2. Via SSH (Secure Shell):
      • Remotely access a Linux machine:
    ssh username@hostname_or_ip

    Example:

    ssh root@192.168.1.10
    1. Graphical Terminal Emulator:
      • On desktop environments, open a terminal emulator (e.g., GNOME Terminal, Konsole). Example:
        • Shortcut: Ctrl + Alt + T (on many systems).

    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

    OperatorPurposeDescription
    Redirect standard outputOverwrites the target file with the output.
    >> Append standard outputAppends the output to the target file instead of overwriting.
    2>Redirect standard errorSends error messages to a file.
    2>>Append standard errorAppends error messages to a file.
    ``Pipe output to another command
    Redirect standard inputReads input from a file instead of the keyboard.
    &>Redirect both stdout and stderrCombines stdout and stderr to a single destination (overwrite).
    &>>Append both stdout and stderrCombines 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 output
    • command > file 2>&1: Sends standard output and the error output to a file
    • command &> file: Sends standard output and the error output to a file
    • command 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 file
    • command 2>> file: Appends error output to a file
    • command >> file 2>&1: Appends standard output and error output to a file
    • command &>> file: Appends standard output and error output to a file
    • command 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 | command3

    2. 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.log

    2.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.log

    3.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

    OptionDescription
    -iCase-insensitive search.
    -vInvert the match (show lines that don’t match).
    -cCount the number of matching lines.
    -nShow line numbers for matches.
    -r or -RRecursive search in directories.
    -lList file names with matches.
    -EUse 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/passwd
    grep -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)

    PatternMeaning
    ^abcLines starting with abc.
    abc$Lines ending with abc.
    a.bMatches 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.

    PatternMeaning
    a+Matches one or more occurrences of a.
    a{2,}Matches 2 or more occurrences of a.
    `ab`
    (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

    1. Find lines in /etc/passwd starting with a.
    2. Count the number of lines in /var/log/messages containing failed.
    3. 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://developers.redhat.com/articles/2022/09/14/beginners-guide-regular-expressions-grep#what_are_regular_expressions__and_what_isgrep

    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-clients

    2. 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 sshd

    3. 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_host
    Example:
    ssh root@192.168.1.100

    4. Changing the Default SSH Port

    By default, SSH runs on port 22. For security, you can change this to a custom port.

    Steps:
    1. Edit the SSH configuration file:
    sudo vi /etc/ssh/sshd_config
    1. Locate the line starting with #Port 22 and change it to a custom port (e.g., Port 2222). Remove the # to uncomment the line:
    Port 2222
    1. Restart the SSH service:
    sudo systemctl restart sshd
    Connecting with a Custom Port:

    Use the -p option to specify the port.

    ssh -p 2222 root@192.168.1.100

    5. Generating and Using SSH Keys

    Using SSH keys enhances security by replacing password authentication with public-key authentication.

    Steps to Generate SSH Keys:
    1. Generate an SSH key pair on the client system:
    ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa
    1. Copy the public key to the remote server:
    ssh-copy-id username@remote_host
    Connect Without Password:

    Once the public key is copied, you can log in without a password:

    ssh username@remote_host

    6. 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 2222
    Connecting with Short Name:
    ssh remote_server

    7. Secure SSH Configuration (Best Practices)

    1. Disable root login: Edit /etc/ssh/sshd_config and set:
    plaintext
    PermitRootLogin no

    Restart 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 no in /etc/ssh/sshd_config to enforce key-based authentication.
    • Limit failed login attempts: Use a tool like fail2ban to block IPs after repeated failed login attempts:
     
     
    sudo yum install -y fail2ban

    8. Troubleshooting SSH

    1. Check Connectivity:
    ping remote_host
    1. Test SSH Connection Verbosely:
    ssh -v username@remote_host
    1. Check SSH Logs: On the server:
    sudo tail -f /var/log/secure

    Example Scenarios

    1. Copy Files Over SSH: Use scp to 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_host

    These 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 sshd

    SSH client installation (server_B)

    dnf install -y openssh-clients

    Login SSH

    Configure key based authentication via SSH

    create keys for the client machine (server_B)

    ssh-keygen
    Generating 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

    filename
    id_rsaprivate key (do not share)
    id_rsa.pubpublic 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

    FeatureSysV init Runlevelsystemd TargetExample Commands
    DefinitionRunlevels define the state of the system.Targets define states or groups of services.N/A
    Management Tool/etc/inittabsystemctlN/A
    Default State ConfigurationEdit /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 Commandinit <runlevel>systemctl isolate <target>SysV: init 3
    systemd: systemctl isolate multi-user.target
    Runlevels/Targets DescriptionNumerical identifiers (0-6).Named targets (descriptive names).N/A
    Example States0: Haltpoweroff.target: HaltSysV: init 0
    systemd: systemctl isolate poweroff.target
    1: Single-user moderescue.target: Single-user modeSysV: init 1
    systemd: systemctl isolate rescue.target
    3: Multi-user modemulti-user.target: Multi-user mode (no GUI)SysV: init 3
    systemd: systemctl isolate multi-user.target
    5: Multi-user + GUIgraphical.target: Multi-user + GUISysV: init 5
    systemd: systemctl isolate graphical.target
    6: Rebootreboot.target: RebootSysV: init 6
    systemd: systemctl isolate reboot.target
    Enable/Disable ServicesUse /etc/rc.d or /etc/init.d scripts.Use systemctl enable/disable.SysV: chkconfig httpd on
    systemd: systemctl enable httpd
    Parallel StartupNo, runs scripts sequentially.Yes, supports parallel service startup.N/A
    Service MonitoringLimited; 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-default

    Command to set the default to multiuser target:

    systemctl set-default multi-user.target

    Command to switch to multiuser target immediately:

    sudo systemctl isolate multi-user.target

    Log 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_ip

    Switch Users in Multiuser Targets

    1. Switch User Temporarily:
      • Use the su command to switch to another user without logging out: su - username
      • The - option ensures the user’s environment variables and shell are loaded.
    2. Switch to the Superuser (Root):
      • If you have superuser privileges, use: su -
      • Enter the root password when prompted.
    3. Switch with sudo:
      • To execute a single command as another user: sudo -u username command
      • Example: sudo -u apache systemctl restart httpd
    4. Log in as a Different User:
      • Use logout or Ctrl+D to log out of the current session.
      • Log in as a different user when prompted.

    Best Practices for User Switching

    • Avoid using the root account directly unless necessary; use sudo for 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

    1. Create an Archive:
    tar -cvf archive.tar file1 file2 directory/
    1. archive.tar: Name of the archive.
    2. file1, file2, and directory/: Files and directories to archive.
    3. List Contents of an Archive:
    tar -tvf archive.tar
    1. Extract an Archive:
    tar -xvf archive.tar
    1. Create a Compressed Archive with gzip:
    tar -czvf archive.tar.gz file1 file2 directory/
    1. Extract a Compressed Archive with gzip:
    tar -xzvf archive.tar.gz
    1. Create a Compressed Archive with bzip2:
    tar -cjvf archive.tar.bz2 file1 file2 directory/
    1. Extract a Compressed Archive with bzip2:
    tar -xjvf archive.tar.bz2

    2. 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

    1. Compress a File:
    gzip file.txt

    Result: Creates file.txt.gz.

    1. Compress Multiple Files:
    gzip file1 file2

    Result: Creates file1.gz and file2.gz.

    1. Decompress a File:
    gunzip file.txt.gz

    Result: Restores file.txt.

    1. Keep the Original File While Compressing:
    gzip -c file.txt > file.txt.gz

    3. 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

    1. Compress a File:
    bzip2 file.txt

    Result: Creates file.txt.bz2.

    1. Compress Multiple Files:
    bzip2 file1 file2

    Result: Creates file1.bz2 and file2.bz2.

    1. Decompress a File:
    bunzip2 file.txt.bz2

    Result: Restores file.txt.

    1. Keep the Original File While Compressing:
    bzip2 -c file.txt > file.txt.bz2

    4. Combining Utilities

    You can use tar with gzip or bzip2 for both archiving and compressing in a single step.

    Examples

    1. Archive and Compress with gzip:
    tar -czvf archive.tar.gz file1 file2 directory/
    1. Archive and Compress with bzip2:
    tar -cjvf archive.tar.bz2 file1 file2 directory/
    1. Extract gzip Compressed Archive:
    tar -xzvf archive.tar.gz
    1. Extract bzip2 Compressed Archive:
    tar -xjvf archive.tar.bz2

    Summary Table of Commands

    TaskCommand
    Create tar archivetar -cvf archive.tar file1 file2
    Extract tar archivetar -xvf archive.tar
    Compress with gzipgzip file.txt
    Decompress gzip filegunzip file.txt.gz
    Compress with bzip2bzip2 file.txt
    Decompress bzip2 filebunzip2 file.txt.bz2
    Archive + gzip compressiontar -czvf archive.tar.gz file1 file2
    Archive + bzip2 compressiontar -cjvf archive.tar.bz2 file1 file2
    Extract tar.gztar -xzvf archive.tar.gz
    Extract tar.bz2tar -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.
    • 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.

    Commands to Create Links

    1. Create a Hard Link

    ln [source_file] [hard_link]

    Example:

    touch original.txt

    ln 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 -li

    Output:

    
    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.txt

    Both 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 -l

    Output:

    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

    FeatureHard LinkSoft Link
    Inode SharedYesNo
    Works Across File SystemsNoYes
    Link to DirectoriesNoYes
    Broken if Original is DeletedNoYes

    Practical Examples

    1. Demonstrating Hard Links

    1. Create a file and add content:
    echo "Hello, RHCSA!" > original.txt
    1. Create a hard link:
    ln original.txt hardlink.txt
    1. Modify the content via the hard link:
    echo "Adding more content" >> hardlink.txt
    1. Verify both files:
    cat original.txt
    
    cat hardlink.txt

    Output:

    Hello, RHCSA!
    Adding more content

    2. Demonstrating Soft Links

    1. Create a symbolic link:
    ln -s original.txt softlink.txt
    1. View the link:
    ls -l
    1. Delete the source file:
    rm original.txt
    1. Access the soft link:
    cat softlink.txt

    Output:

    cat: softlink.txt: No such file or directory

    Important 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.txt

    Explanation:

    • -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: User
    • g: Group
    • o: Others
    • a: All (u, g, and o)
    • Operation:
    • +: Add permission
    • -: Remove permission
    • =: Set exact permission
    Examples:
    1. 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.txt

    b. 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, execute
    • 6 (4+2): Read, write
    • 5 (4+1): Read, execute
    • 4: Read only
    Syntax:
    chmod [numeric_permissions] file
    Examples:
    1. 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.txt

    3. 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] file
    Example:
    chown john file.txt

    b. Changing Group

    Syntax:
    chgrp [group] file
    Example:
    chgrp developers file.txt

    c. Changing Ownership and Group Simultaneously

    Syntax:
    chown [user]:[group] file
    Example:
    chown john:developers file.txt

    4. Recursive Permission Changes

    Use the -R option with chmod, chown, or chgrp to apply changes recursively to directories and their contents.

    Example:

    1. Apply 755 to all files and directories recursively:
    chmod -R 755 /path/to/directory
    • Change ownership recursively:
    chown -R john:developers /path/to/directory

    5. Special Notes

    • Default Permissions: Use the umask command to set default permissions for new files and directories.
    • View Effective Permissions: Use getfacl to view detailed permissions, including ACLs (Access Control Lists).
    • Testing Permissions: Use the su or sudo -u commands 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:

    1. man (Manual Pages): Concise, sectioned reference for commands and system components.
    2. info: More detailed, often hyperlinked, documentation for GNU utilities.
    3. 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

    1. Basic Usage
    man ls

    Displays the manual page for the ls command.

    1. Search in a Specific Section
    man 5 passwd

    Displays information about the /etc/passwd file format (from section 5).

    1. Search for a Keyword
    man -k file

    Lists all manual pages related to “file”. Equivalent to:

    apropos file
    1. View All Matching Pages If multiple commands share a name, use -a:
    man -a printf

    View 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

    1. View Documentation for a Command
    info ls

    Opens a detailed document for the ls command, often more expansive than man.

    1. Search in info
      • Press Ctrl+S to search for a keyword.
      • Use n to jump to the next match.
    2. Navigate info
      • Use arrow keys or Tab to move between links.
      • Press Enter to follow a link.
      • Press u to go up one level.
    3. List Available Topics
    info coreutils

    Displays 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

    1. List Contents
    ls /usr/share/doc

    Displays directories for each installed package.

    1. View Files for a Specific Package
    ls /usr/share/doc/httpd

    Lists files related to the httpd (Apache) package.

    1. Read a File
    cat /usr/share/doc/httpd/README
    1. Search for Documentation
    find /usr/share/doc -type f -iname "*example*"

    Finds files with “example” in their name.


    Best Practices for System Documentation

    1. Start with man: Use it for quick reference and syntax details.
    2. Refer to info: When deeper details or examples are needed for GNU utilities.
    3. Check /usr/share/doc: For package-specific details, configuration samples, and troubleshooting tips.

    Quick Example: Understanding sshd Configuration

    1. View the man Page
    man sshd_config

    Learn about directives in the /etc/ssh/sshd_config file.

    1. Search for an Option

    /PermitRootLogin

    Locate the section on PermitRootLogin.

    1. Check /usr/share/doc
    ls /usr/share/doc/openssh
    cat /usr/share/doc/openssh/README

    Look for additional examples or details about the OpenSSH server.


    Tips for RHCSA Exam

    1. Practice Navigation:
      • Be comfortable with man and info for commonly used commands.
    2. Explore /usr/share/doc:
      • Familiarize yourself with the type of files stored for key packages.
    3. 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.

    Leave a Reply

    Your email address will not be published. Required fields are marked *