Unit 5 subjective questions Shell Features
CSE105 — Creative Engineering Workshop 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define pattern matching in the context of the Unix/Linux shell. Explain why wildcards are useful when working with files.
Model answer
Pattern Matching refers to the shell's ability to match filenames against special characters (called wildcards or metacharacters) so that a single command can operate on multiple files at once.
Why wildcards are useful:
- Efficiency: A single command can act on dozens of files instead of typing each name.
- Flexibility: You can select files based on partial names, extensions, or character ranges.
- Automation: Scripts can process groups of files dynamically.
Common Wildcards:
*— matches zero or more characters.?— matches exactly one character.[...]— matches any one character from the enclosed set.
Example:
Bashls *.txt # lists all files ending in .txt rm file?.log # removes file1.log, fileA.log, etc.The shell performs this matching (called globbing) before passing the expanded names to the command.
-
Question 2 of 20
Explain the use of the
*and?wildcard characters with suitable examples. How do they differ?Model answer
The
*(asterisk) Wildcard:- Matches zero or more characters (any string, including an empty one).
- Does not match a leading dot in hidden files by default.
Example:
Bashls a* # matches a, ab, abc, apple, etc. ls *.c # matches all files ending in .cThe
?(question mark) Wildcard:- Matches exactly one character.
Example:
Bashls file?.txt # matches file1.txt, fileA.txt (single char) ls ??.sh # matches any 2-character name ending in .shKey Difference:
Wildcard Matches Count of characters *Any string 0 or more ?Any single char Exactly 1 Thus
?is more restrictive since it requires a character in that exact position, while*is flexible in length. -
Question 3 of 20
Describe the use of character classes (
[...]) in shell pattern matching. Illustrate with ranges and negation.Model answer
Character Classes (
[...]):The square brackets match any one character from the enclosed set.
1. Simple Set:
Bashls file[123].txt # matches file1.txt, file2.txt, file3.txt2. Ranges: A hyphen defines a range.
Bashls [a-z]* # files starting with any lowercase letter ls file[0-9] # file0 to file9 ls [A-Za-z]* # files starting with any letter3. Negation: A
!or^at the start negates the set.Bashls [!0-9]* # files NOT starting with a digit4. POSIX Character Classes:
Bashls [[:digit:]]* # files starting with a digit ls [[:upper:]]* # files starting with an uppercase letterKey Points:
- Matches exactly one character position.
- Ranges depend on the locale's collating order.
- Very useful for selecting files by a specific character group.
-
Question 4 of 20
Distinguish between wildcards and regular expressions in the Unix shell.
Model answer
Although both use special symbols, wildcards (globbing) and regular expressions (regex) serve different purposes and behave differently.
Aspect Wildcards (Globbing) Regular Expressions Used by Shell for filename matching Tools like grep,sed,awk*meansZero or more of any char Zero or more of the preceding char ?meansExactly one character Zero or one of preceding char .Literal dot Any single character Applied to Filenames Text/content of files Anchoring Implicit (whole name) Uses ^and$Example of difference:
- Wildcard:
ls a*→ filenames starting witha. - Regex:
grep 'a*' file→ matches lines with zero or moreas.
Summary: Wildcards operate on filenames and are expanded by the shell; regex operates on text content and is interpreted by individual programs.
- Wildcard:
-
Question 5 of 20
What is I/O redirection? Explain the three standard file descriptors used by the shell.
Model answer
I/O Redirection is a shell feature that changes the default sources and destinations of a command's input and output streams, allowing them to be read from or written to files instead of the terminal.
The Three Standard File Descriptors:
- Standard Input (stdin) — descriptor
0: Default source of input, normally the keyboard. - Standard Output (stdout) — descriptor
1: Default destination of normal output, normally the terminal screen. - Standard Error (stderr) — descriptor
2: Destination for error messages, also normally the terminal.
Why redirection is useful:
- Save command output to a file.
- Supply input from a file instead of typing.
- Separate normal output from error messages.
Example:
Bashsort < data.txt # stdin from file ls > list.txt # stdout to file gcc prog.c 2> err.txt # stderr to fileEach descriptor can be independently redirected, giving fine control over data flow.
- Standard Input (stdin) — descriptor
-
-
Question 6 of 20
Explain output redirection using
>and>>. How do they differ?Model answer
Output redirection sends the standard output of a command to a file instead of the terminal.
1. The
>Operator (Overwrite):- Redirects stdout to a file.
- Creates the file if it does not exist.
- Overwrites (truncates) the file if it already exists.
Bashls > files.txt # creates or replaces files.txt date > log.txt # log.txt now contains only the date2. The
>>Operator (Append):- Redirects stdout to a file.
- Creates the file if it does not exist.
- Appends to the end of the file if it exists (existing content preserved).
Bashdate >> log.txt # adds date to end of log.txt echo "Done" >> log.txtKey Difference:
Operator If file exists Purpose >Overwrites content Fresh output >>Appends content Logging / accumulation Caution:
>can cause data loss if used on an important existing file. -
Question 7 of 20
Explain input redirection using
<with an example. How is it different from a here-document (<<)?Model answer
Input Redirection (
<):Redirects the standard input of a command so it reads from a file instead of the keyboard.
Bashwc -l < data.txt # counts lines by reading data.txt as stdin sort < names.txt # sorts contents of names.txtHere the command does not receive the filename as an argument — the shell connects the file to stdin.
Here-Document (
<<):Allows you to supply multiple lines of inline input directly within a script or command until a delimiter word is reached.
Bashcat << END Hello World This is a here-document. ENDEverything between
<< ENDand theENDmarker is fed as stdin.Difference:
Feature <(Input Redirect)<<(Here-Document)Source An existing file Inline text in script Terminated by End of file Delimiter word Use case Feeding file data Embedding text/scripts Here-String (
<<<): A related form feeds a single string:Bashwc -w <<< "count these words" -
Question 8 of 20
Describe how standard error redirection works. Explain how to redirect both stdout and stderr to the same file.
Model answer
Standard Error (stderr) uses file descriptor
2. By default it appears on the terminal even when stdout is redirected.Redirecting stderr alone:
Bashgcc prog.c 2> errors.txt # only error messages go to file command 2>> errors.txt # append errorsRedirecting stderr to a null device (discard):
Bashcommand 2> /dev/nullRedirecting BOTH stdout and stderr to the same file:
Method 1 — traditional (order matters):
Bashcommand > out.txt 2>&1Here
2>&1means redirect descriptor 2 to wherever descriptor 1 currently points (the file). The order is important: stdout must be redirected first.Method 2 — Bash shorthand:
Bashcommand &> out.txt # both stdout and stderr command &>> out.txt # append bothCommon Mistake:
Bashcommand 2>&1 > out.txt # WRONG order: stderr still goes to terminalThis is because
2>&1is applied before stdout is redirected to the file. -
Question 9 of 20
What is a pipe in the shell? Explain its working with a suitable example.
Model answer
Pipe (
|):A pipe is a shell mechanism that connects the standard output of one command directly to the standard input of another, allowing commands to be chained so that data flows from one to the next without intermediate temporary files.
Syntax:
Bashcommand1 | command2Working:
- The shell creates an in-memory buffer (the pipe).
command1's stdout is connected to this buffer.command2's stdin reads from this buffer.- Both commands run concurrently.
Example:
Bashls -l | grep ".txt"Here the long listing produced by
ls -lis fed togrep, which filters lines containing.txt.Another Example:
Bashcat file.txt | wc -l # count lines in file.txtAdvantages:
- No temporary files needed.
- Efficient use of memory.
- Encourages the Unix philosophy of small, single-purpose tools working together.
-
Question 10 of 20
Explain pipe chaining (multiple pipes) with an example. How does data flow through the chain?
Model answer
Pipe Chaining connects several commands using multiple
|operators so that output flows through a sequence of processing stages, each transforming the data before passing it on.Syntax:
Bashcmd1 | cmd2 | cmd3 | cmd4Data Flow:
cmd1output →cmd2inputcmd2output →cmd3inputcmd3output →cmd4input- All commands run simultaneously, forming a data-processing pipeline.
Example:
Bashcat /etc/passwd | grep "/bin/bash" | cut -d: -f1 | sort | wc -lStage-by-stage explanation:
cat /etc/passwd— outputs the whole file.grep "/bin/bash"— keeps lines of bash users.cut -d: -f1— extracts the username field.sort— sorts the usernames.wc -l— counts the number of such users.
Advantages:
- Complex tasks built from simple tools.
- Readable, modular command construction.
- No intermediate files required.
-
Question 11 of 20
Compare pipes with redirection. When would you use each?
Model answer
Both pipes and redirection control data flow, but they connect to different endpoints.
Aspect Redirection ( >,<)Pipe ( |)Connects Command ↔ File Command ↔ Command Storage Uses a file on disk Uses in-memory buffer Persistence Data saved permanently Data is transient Number of commands One command + file Two or more commands Example ls > out.txtls | grep txtWhen to use Redirection:
- To save output for later use.
- To read input from an existing file.
- To log errors or output.
When to use Pipes:
- To process output of one command with another immediately.
- To build multi-stage data pipelines.
- When no permanent storage is needed.
Combined Example:
Bashsort < names.txt | uniq > result.txtHere redirection reads input and writes final output, while the pipe processes data in between.
-
Question 12 of 20
What is the
teecommand? Explain how it is used with pipes.Model answer
The
teeCommand:teereads from standard input and writes simultaneously to standard output and to one or more files. Its name comes from the T-shaped plumbing joint that splits a flow.Syntax:
Bashcommand | tee file.txtWorking:
- Data coming through the pipe is written to
file.txt. - The same data is also passed to the terminal (or the next command).
Example 1 — Save and display:
Bashls -l | tee listing.txtShows the listing on screen and saves it to
listing.txt.Example 2 — Append mode (
-a):Bashdate | tee -a log.txtExample 3 — In the middle of a pipeline:
Bashcat data.txt | tee raw.txt | grep "error" | wc -lHere
teesaves the raw data while the pipeline continues processing.Uses:
- Logging intermediate results.
- Debugging pipelines.
- Writing to a file and screen at once.
- Data coming through the pipe is written to
-
Question 13 of 20
Explain filename expansion (globbing) and the sequence of steps the shell follows to expand wildcards before executing a command.
Model answer
Filename Expansion (Globbing):
This is the process by which the shell replaces wildcard patterns with the matching filenames before the command actually runs.
Steps the Shell Follows:
- Scan the command line for wildcard characters (
*,?,[...]). - Search the relevant directory for filenames matching the pattern.
- Replace the pattern with the sorted list of matching filenames.
- Pass the expanded list as arguments to the command.
- If no match is found, most shells leave the pattern unchanged (in Bash by default).
Example:
Bashrm *.tmp- Shell finds
a.tmp b.tmp c.tmp. - Command becomes
rm a.tmp b.tmp c.tmp.
Important Notes:
- The command never sees the wildcards — it only sees expanded names.
- Hidden files (starting with
.) are not matched by*unless explicitly stated. - Quoting a pattern (e.g.,
"*.txt") prevents expansion. - The
nullgloboption makes unmatched patterns expand to nothing.
- Scan the command line for wildcard characters (
-
Question 14 of 20
Describe various methods to prevent or disable wildcard expansion in the shell. Why is this sometimes necessary?
Model answer
Sometimes we want the shell to treat wildcard characters literally instead of expanding them.
Why disable expansion?
- To pass a pattern to a program (e.g.,
find,grep) that will interpret it itself. - To use special characters as literal text.
- To prevent unexpected matches.
Methods to Prevent Expansion:
1. Single Quotes (
' '): Strongest — nothing inside is expanded.Bashecho '*.txt' # prints *.txt literally2. Double Quotes (
" "): Prevents globbing (but allows variable expansion).Bashecho "*.txt" # prints *.txt3. Backslash (
\): Escapes a single character.Bashecho \* # prints *4.
set -f/set -o noglob: Disables globbing for the whole session.Bashset -f ls *.txt # * treated literally set +f # re-enableExample use with find:
Bashfind . -name "*.c" # quotes let find interpret the pattern itselfQuoting ensures the pattern reaches
findintact rather than being expanded by the shell. - To pass a pattern to a program (e.g.,
-
Question 15 of 20
Write shell commands (with explanation) to accomplish the following tasks using wildcards, redirection, and pipes:
- List all
.logfiles. - Count how many
.cfiles exist. - Save a sorted, unique list of users.
- Find the 5 largest files in a directory.
Model answer
1. List all
.logfiles:Bashls *.logThe
*wildcard matches any name ending in.log.2. Count how many
.cfiles exist:Bashls *.c | wc -lls *.clists all C files (one per line via pipe).wc -lcounts the lines = number of files.
3. Save a sorted, unique list of users:
Bashcut -d: -f1 /etc/passwd | sort | uniq > users.txtcutextracts usernames.sortorders them.uniqremoves duplicates.>saves the result tousers.txt.
4. Find the 5 largest files in a directory:
Bashls -lS | head -6ls -lSsorts files by size (largest first).head -6shows the top lines (1 header + 5 files).
Alternative using du:
Bashdu -ah . | sort -rh | head -5These examples combine wildcards, pipes, and redirection to solve real tasks.
- List all
-
Question 16 of 20
Explain in detail the working of a pipeline internally, including how the shell uses processes and buffers. Illustrate with a diagram-style explanation.
Model answer
Internal Working of a Pipe:
When you run
cmd1 | cmd2, the shell performs several low-level operations to connect the two processes.Steps Performed by the Shell:
- Create a pipe using the
pipe()system call. This returns two file descriptors:- A read end (
fd[0]) - A write end (
fd[1])
- A read end (
- Fork two child processes (one per command).
- For cmd1: connect its stdout (fd 1) to the write end of the pipe using
dup2(). - For cmd2: connect its stdin (fd 0) to the read end of the pipe.
- Close unused pipe ends in each process.
- Execute each command via
exec(). - Both commands run concurrently; data flows through a kernel buffer.
Diagram-style Flow:
+--------+ stdout [ PIPE BUFFER ] stdin +--------+
| cmd1 | ---------> | kernel memory | ------> | cmd2 |
+--------+ +---------------+ +--------+Key Points:
- The pipe buffer is maintained in kernel memory, typically a few kilobytes.
- If the buffer fills,
cmd1blocks untilcmd2reads (flow control). - If
cmd2finishes early,cmd1may receive a SIGPIPE. - No disk file is created, making pipes fast and memory-efficient.
This mechanism embodies the Unix philosophy of composing small tools into powerful pipelines.
- Create a pipe using the
-
Question 17 of 20
Distinguish between
>,>>,2>,&>, and2>&1redirection operators with examples.Model answer
These operators control where output and error streams are directed.
Operator Meaning Example >Redirect stdout, overwrite file ls > out.txt>>Redirect stdout, append to file ls >> out.txt2>Redirect stderr, overwrite file cmd 2> err.txt&>Redirect both stdout & stderr cmd &> all.txt2>&1Redirect stderr to stdout's target cmd > all.txt 2>&1Detailed Explanation:
>— Normal output only; existing content is lost.
Bashdate > log.txt>>— Normal output appended; preserves old data.
Bashdate >> log.txt2>— Only error messages (descriptor 2).
Bashgcc a.c 2> errors.txt&>— Bash shortcut for both streams.
Bashmake &> build.log2>&1— Send stderr wherever stdout points. Order matters:
Bashcmd > file.txt 2>&1 # both to file cmd 2>&1 > file.txt # stderr to terminal (wrong order)Summary:
1= stdout,2= stderr;>overwrites,>>appends, and&groups both streams. -
Question 18 of 20
Explain the brace expansion
{...}feature and how it differs from wildcard character classes[...].Model answer
Brace Expansion (
{...}):Brace expansion generates a set of strings by combining a fixed prefix/suffix with the comma-separated (or range) items inside the braces. It happens before filename expansion and does not require files to exist.
Examples:
Bashecho file{1,2,3}.txt # file1.txt file2.txt file3.txt echo {a..e} # a b c d e (sequence) echo {1..5} # 1 2 3 4 5 mkdir project/{src,bin,doc} # creates three directoriesCharacter Class (
[...]):This is a wildcard that matches a single existing filename character.
Bashls file[123].txt # matches only EXISTING file1.txt etc.Key Differences:
Feature Brace {}Class []Purpose Generates strings Matches existing filenames Files must exist? No Yes Matches count Produces multiple strings Matches one character Example {a,b,c}→ a b c[abc]→ one of a/b/cSummary: Brace expansion creates text combinations, while character classes filter existing filenames during globbing.
-
Question 19 of 20
Discuss common errors and pitfalls when using redirection and pipes, and how to avoid them.
Model answer
Redirection and pipes are powerful but error-prone. Below are frequent pitfalls and their solutions.
1. Accidental Overwrite with
>:Bashsort data.txt > data.txt # WRONG: truncates file before reading- The shell empties
data.txtfirst, losing the data. - Fix: Use a temp file or
sort -o data.txt data.txt.
2. Wrong order of
2>&1:Bashcmd 2>&1 > out.txt # stderr still goes to terminal- Fix: Put
2>&1after the stdout redirect:cmd > out.txt 2>&1.
3. Piping to commands that don't read stdin:
Bashls | cd /tmp # cd ignores piped input- Fix: Use
xargswhen a command expects arguments:ls | xargs rm.
4. Using
>when append>>is needed:- Overwrites logs. Fix: Use
>>for logging.
5. Unquoted filenames with spaces:
- Wildcards may break on spaces. Fix: Quote variables and use
find ... -print0 | xargs -0.
6. Broken pipe (SIGPIPE): Occurs when the reader exits early (e.g.,
| head). Usually harmless.Best Practices:
- Never redirect a file to itself.
- Remember descriptor order.
- Use
teeto inspect intermediate data. - Quote patterns to control expansion.
- The shell empties
-
Question 20 of 20
Design a single command pipeline that reads a web-server access log, extracts the IP addresses, counts how many times each IP appears, and displays the top 3 most frequent IPs. Explain each stage.
Model answer
The Pipeline:
Bashcat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -3Stage-by-Stage Explanation:
-
cat access.log— Outputs the entire log file to the pipeline. (Could also be replaced byawk '{print $1}' access.logdirectly.) -
awk '{print $1}'— Extracts the first field of each line, which in a standard access log is the client IP address. -
sort— Sorts the IP addresses so that identical IPs become adjacent. This is required before counting duplicates. -
uniq -c— Collapses adjacent duplicate lines and prefixes each with a count of occurrences. -
sort -rn— Sorts numerically (-n) in reverse (-r) so the highest counts come first. -
head -3— Displays only the top 3 lines (the three most frequent IPs).
Sample Output:
152 192.168.1.10
98 10.0.0.5
45 172.16.0.2Why this works well:
- Each tool does one job (Unix philosophy).
- No temporary files are created.
- The pipeline is easily modified, e.g., change
head -3tohead -10for the top 10.
This demonstrates the power of pipe chaining combined with text-processing utilities.
-
That's unit 5
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 5 of CSE105 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 5 of CSE105 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.