Essential CLI Tools
This section covers core Linux command-line utilities, stream redirection, shell environment configurations, history expansion, manual page indices, and basic text editing for RHCSA preparation.
Theory Questions
1. How do you redirect both standard output and standard error to a file?
Redirect stdout using > and redirect stderr to stdout using 2>&1, or use the &> shortcut.
- Command(s):
command > file.txt 2>&1orcommand &> file.txt - Why:
>redirects standard output (file descriptor 1);2>&1points standard error (file descriptor 2) to the same stream destination.&>is a concise Bash shortcut achieving the same outcome. - Gotchas: Redirection order matters.
2>&1 > fileredirects stderr to the current terminal stream before redirecting stdout to the target file. - Verify:
ls /doesnotexist > /tmp/test.txt 2>&1; cat /tmp/test.txt
2. How do you set a local variable that is available for every user in every shell session?
Place the variable assignment inside a script within the /etc/profile.d/ directory without using the export keyword.
- Command(s):
echo 'COLOR=red' > /etc/profile.d/color.sh - Why: Scripts inside
/etc/profile.d/are sourced globally for all users during shell initialization. Omittingexportkeeps the variable local to the shell instead of an environment variable. - Gotchas: Using
exportpromotes the variable to an environment variable passed to child processes. Defining variables in~/.bashrcapplies only to a single user. - Verify:
cat /etc/profile.d/color.sh
3. How do you diagnose why a script with executable permissions fails to run by name?
Check whether the target directory exists in $PATH and verify the script’s shebang line.
- Command(s):
echo $PATHandhead -n 1 script.sh - Why: Invoking commands directly by name requires their path to exist within
$PATH. Additionally, the script must start with a valid interpreter instruction (e.g.,#!/bin/bash). - Gotchas: The current working directory (
.) is intentionally excluded from$PATHby default for security reasons. - Verify:
which script.sh(returns no path if the containing directory is missing from$PATH).
4. How do you pipe the output of ls as input to the less command?
Connect the output stream of ls to less using the pipe (|) operator.
- Command(s):
ls | less - Why: The pipe operator (
|) routes standard output from the left process directly into standard input of the right process. - Gotchas: Piping output strips terminal formatting colors unless explicitly forced by command arguments.
- Verify:
ls | less(pressqto exit).
5. How do you remove an accidentally typed password from Bash history?
Delete the specific entry index using history -d.
- Command(s):
history -d <line_number> - Why:
history -dremoves a targeted line number from the active shell’s in-memory history list. - Gotchas: If the shell session has already closed and written to disk, you must edit
~/.bash_historydirectly. To avoid recording sensitive inputs, setHISTCONTROL=ignorespaceand prefix commands with a space. - Verify:
history | grep password
6. What are the valid and invalid methods to repeat a command from history?
Use history expansion operators starting with !; avoid using globbing or comment symbols.
- Command(s):
- Valid:
!!(repeat last command),!n(repeat line n),!string(repeat last command starting with string),?string?(repeat last command containing string),Up Arrow. - Invalid:
*string,#string.
- Valid:
- Why: Bash reserves
!for history expansion routines.*performs glob pattern matching and#denotes comments. - Gotchas: Do not confuse history expansion (
!) with wildcard globbing (*). - Verify:
echo !!
7. What items can Bash completion be used for?
Bash completion handles commands, file paths, variables, network hosts, and utility-specific subcommands.
- Command(s):
rpm -q bash-completion(pressTabtwice to test completion) - Why: Tab completion queries internal shell tables, system binaries, environment arrays, and extended completion rule sets provided by the
bash-completionpackage. - Gotchas: Advanced option auto-completion requires the explicit installation of the
bash-completionpackage. - Verify:
rpm -q bash-completion
8. How do you replace every occurrence of a word in a file using vim?
Run a global substitution command across all lines in Normal mode.
- Command(s):
:%s/oldword/newword/g(in Normal mode) - Why:
%targets every line in the file buffer,sspecifies the substitute action, andgreplaces all instances within each matching line. - Gotchas: Omitting
greplaces only the first occurrence per line. Omitting%executes substitution solely on the active cursor line. - Verify: Open the target file in
vim, run the command, and inspect the modifications.
9. How do you display a message to all users who log in to a shell session?
Write the target announcement text into /etc/motd.
- Command(s):
echo "Welcome to the system" > /etc/motd - Why:
/etc/motd(Message of the Day) is automatically read and displayed by system login routines following successful authentication. - Gotchas: Using
wallbroadcasts messages exclusively to users currently logged in, not to future logins. - Verify:
cat /etc/motd
10. How do you fix the “nothing appropriate” error message when using man -k?
Rebuild the system manual page database index caches.
- Command(s):
mandb(ormandb -c) - Why:
man -ksearches the whatis database. If the index is empty or corrupted, queries return “nothing appropriate”. Runningmandbindexing updates these keyword caches. - Gotchas: Running
man -udoes not rebuild index databases from scratch. - Verify:
man -k passwd
11. What is a variable in a shell environment?
A variable is a named storage pointer in memory used to reference values, paths, or execution state flags.
- Command(s):
MYVAR="test"; echo $MYVAR - Why: Variables allow commands and automated scripts to reference dynamic data parameters programmatically.
- Gotchas: Shell variables remain local to the current shell process unless exported as environment variables.
- Verify:
echo $MYVAR
12. How do you find the correct man page based on keyword usage?
Query manual page index summaries using man -k or apropos.
- Command(s):
man -k keywordorapropos keyword - Why: These tools search whatis database descriptions and return man pages matching target terms.
- Gotchas: Running
man keywordmatches precise man page names rather than searching header descriptions. - Verify:
man -k network
13. How do you set a variable for a specific user upon login?
Append an export declaration to the target user’s ~/.bash_profile.
- Command(s):
echo 'export MYVAR="value"' >> ~/.bash_profile - Why:
~/.bash_profileis executed specifically for user login shell instances, setting environment variables for that account. - Gotchas: Adding configurations to
/etc/profileaffects all system users globally. - Verify:
grep MYVAR ~/.bash_profile
14. How do you access documentation maintained with the Techinfo system?
Use the info reader command.
- Command(s):
info <command> - Why: GNU project tools maintain structural documentation formatted for the Texinfo navigation system accessed via
info. - Gotchas:
mandisplays standard troff/groff manual pages and lacks hyperlinked Texinfo node navigation. - Verify:
info bash
15. Which file stores the saved command history for Bash?
The location is designated by $HISTFILE, defaulting to ~/.bash_history.
- Command(s):
echo $HISTFILE - Why: Bash reads this environment variable upon initialization to load past execution commands and writes session buffers to it on exit.
- Gotchas: Modifying
$HISTFILEchanges the destination file path for history persistence. - Verify:
echo $HISTFILE
16. How do you update the database containing manual page keywords?
Re-index local man page directories using mandb.
- Command(s):
mandb - Why: Scans system manual paths and updates index databases queried by
man -kandapropos. - Gotchas: Updating system-wide man database caches requires elevated root privileges.
- Verify:
mandb -torman -k <keyword>
17. How do you undo the last modification made in vim?
Press u while operating in Normal mode.
- Command(s):
u(in Normal mode) - Why:
utriggers the built-in undo stack mechanism withinvim. - Gotchas: Attempting to undo while remaining in Insert mode types the character ‘u’ into the text buffer. Press
Escfirst. - Verify: Open
vim, make a text modification, pressEsc, and pressu.
18. How do you suppress error messages from command output?
Redirect standard error to /dev/null.
- Command(s):
command 2> /dev/null - Why:
2>targets standard error (file descriptor 2), sending error text streams into the virtual null device sink. - Gotchas: Using
> /dev/nullsuppresses standard output while leaving standard error displayed on screen. - Verify:
ls /doesnotexist 2>/dev/null
19. How do you read the current contents of the $PATH variable?
Print the environment variable string using echo.
- Command(s):
echo $PATH - Why: Prefixing variable identifiers with
$evaluates and returns their stored values. - Gotchas: Omitting
$evaluates the literal text string"PATH"instead of reading variable memory. - Verify:
echo $PATH
20. How do you repeat the last command containing a specific string?
Execute a reverse history search using ?string? or press Ctrl+R.
- Command(s):
?string?or pressCtrl+Rand typestring - Why:
?string?performs history expansion matching substrings anywhere within prior command strings.Ctrl+Rinvokes interactive reverse search. - Gotchas:
!stringmatches commands that start with the specified text string rather than containing it anywhere. - Verify:
?ls?
Lab Tasks
CLI Practice
Execute essential environment configurations, tool lookups, and stream redirections.
Configuration Steps
# Task 1: Configure persistent variable export for subshell inheritance
echo 'export COLOR=red' >> ~/.bashrc && source ~/.bashrc
# Task 2: Locate user password management documentation
man -k passwd
# Task 3: Execute directory list with combined output and error redirection
cd ~ && ls -al wergihl * &> /tmp/lsoutput
-
Why:
-
~/.bashrcexecutes for every interactive non-login subshell;exportensures child process visibility. -
man -kqueries manual page index descriptions to identify target management tools. -
&>captures both standard output and error streams into a single log file without race conditions. -
Gotchas:
-
Modifying
~/.bash_profileinstead of~/.bashrclimits variables strictly to login shell instances. -
Using
> /tmp/lsoutput 2> /tmp/lsoutputcan create file descriptor locking collisions.
Verification Procedures
Confirm environment state changes and output capture results.
# Verify subshell variable propagation
bash -c 'echo $COLOR'
# Inspect manual page findings for password administrative rights
man passwd
# Inspect captured redirection output content
cat /tmp/lsoutput