Most Frequently asked Interview Questions of shell
Question: How would you use the find
command to search for a file in a specific directory?
Answer:
The find
command in Linux and Unix-like systems is used to search for files and directories based on specific criteria such as name, type, size, and more. To search for a file in a specific directory, you can specify the directory path and use different options to narrow down your search.
Basic Syntax:
find /path/to/directory -name "filename"
/path/to/directory
: The directory where you want to start the search. It could be any directory path, and you can use.
(dot) for the current directory.-name "filename"
: Specifies the name of the file you want to search for. You can use wildcards like*
for partial matches.
Examples:
-
Search for a specific file by name: To search for a file named
example.txt
in a specific directory (/home/user/docs
), use:find /home/user/docs -name "example.txt"
-
Search for files with a specific extension: To find all
.txt
files in a directory (/home/user/docs
), use:find /home/user/docs -name "*.txt"
- This will match all files ending with
.txt
in the/home/user/docs
directory and its subdirectories.
- This will match all files ending with
-
Search in the current directory (and subdirectories) for a file: To search for
example.txt
starting from the current directory (.
), use:find . -name "example.txt"
- The dot (
.
) represents the current directory.
- The dot (
-
Case-insensitive search: If you want to search without worrying about the case (e.g.,
example.txt
,Example.txt
,EXAMPLE.TXT
), use the-iname
option for case-insensitive matching:find /home/user/docs -iname "example.txt"
- This will match
example.txt
,Example.txt
, or any other variation in case.
- This will match
-
Search for files by name and limit the depth of search: If you want to search within a directory but limit the search depth (e.g., only look in the immediate subdirectories, not deeper), use the
-maxdepth
option:find /home/user/docs -maxdepth 1 -name "*.txt"
- This will search only in
/home/user/docs
and not in its subdirectories.
- This will search only in
-
Search for files by type: You can use the
-type
option to search for specific types of files:f
for regular filesd
for directoriesl
for symbolic links
Example:
To search for directories (not files) named
config
in/home/user/docs
:find /home/user/docs -type d -name "config"
-
Search for files modified within a specific time range: You can use options like
-mtime
(modified time) or-ctime
(change time) to search based on file modification times.- For example, to find files modified in the last 7 days:
find /home/user/docs -name "*.txt" -mtime -7
-
Search for files with specific permissions: You can search for files with certain permissions using the
-perm
option.- For example, to find files with
755
permissions:
find /home/user/docs -type f -perm 755
- For example, to find files with
Summary of Common find
Command Options:
Option | Description |
---|---|
-name "pattern" | Search for files that match the specified pattern (case-sensitive). |
-iname "pattern" | Search for files that match the pattern (case-insensitive). |
-maxdepth N | Limit the search to N levels of subdirectories. |
-type f | Search for regular files. |
-type d | Search for directories. |
-mtime N | Search for files modified N days ago. |
-ctime N | Search for files with a change time of N days ago. |
-perm MODE | Search for files with specific permissions (e.g., 755 ). |
Example Commands:
-
Find all
.log
files in/var/log
:find /var/log -name "*.log"
-
Find files modified in the last 10 days:
find /home/user/docs -name "*.txt" -mtime -10
-
Find all directories named
config
in/home/user
:find /home/user -type d -name "config"
By using the find
command with these options, you can efficiently search for files or directories in a specific location based on various criteria.
Question: What is the significance of &
in Shell?
Answer:
In Shell scripting and command-line usage, the &
symbol has several important uses, primarily related to job control and background processes. Here are the key uses and their significance:
1. Running a Command in the Background:
The most common use of &
in Shell is to run a command in the background. When you append &
to a command, the command is executed asynchronously, meaning the terminal prompt returns immediately without waiting for the command to complete. This allows you to run multiple processes simultaneously.
Syntax:
command &
Example:
sleep 10 &
- This will start the
sleep 10
command in the background, and you’ll get your prompt back right away, while thesleep
command continues to run in the background.
You can run multiple commands in the background by appending &
to each one:
command1 & command2 &
Important Notes:
- You can view background jobs by running the
jobs
command. - You can bring a background job to the foreground with the
fg
command, followed by the job number. - To terminate a background process, you can use the
kill
command with the job ID.
2. Running Multiple Commands Sequentially (without waiting for the first to finish):
The &
can also be used to execute multiple commands in sequence, where each command runs in parallel in the background. This allows you to run several commands without waiting for the previous one to complete.
Syntax:
command1 & command2 &
Example:
echo "Starting task 1" & echo "Starting task 2" &
- Both
echo
commands will run concurrently in the background.
3. Running a Command in the Background and Redirecting Output:
When running commands in the background, it’s often helpful to redirect their output (stdout and/or stderr) to a file so that you can monitor the results later, without it cluttering the terminal.
Example:
command > output.txt 2>&1 &
- This runs
command
in the background and redirects both stdout (> output.txt
) and stderr (2>&1
) to a fileoutput.txt
.
4. Combination with Other Control Operators (like &&
and ||
):
While &
by itself is used for background processes, you may encounter the &&
(logical AND) and ||
(logical OR) operators, which are used to combine commands based on success or failure.
-
&&
: Executes the second command only if the first command succeeds (returns exit status 0).command1 && command2
-
||
: Executes the second command only if the first command fails (returns a non-zero exit status).command1 || command2
5. Special Use in Shell Scripting (in Shell functions):
Within shell functions or scripts, you can also use &
when dealing with processes that are explicitly invoked in the background, or when using certain utilities like wait
to manage jobs.
Example:
#!/bin/bash
# Function to run in the background
my_background_function() {
echo "Starting background task..."
sleep 5
echo "Background task completed."
}
my_background_function &
wait
echo "All tasks are completed."
- In this case, the function
my_background_function
runs in the background and the script waits for it to complete usingwait
.
Summary of Key Points:
Use | Description |
---|---|
command & | Runs the command in the background, freeing up the terminal for other tasks. |
command1 & command2 & | Runs multiple commands in parallel, each in the background. |
command > output.txt 2>&1 & | Runs a background command and redirects its output and errors to a file. |
command1 && command2 | Executes command2 only if command1 succeeds. |
`command1 |
Conclusion:
The &
symbol in Shell scripting is essential for background job control. It allows you to run commands in parallel, freeing up the terminal for other tasks, and can be combined with other operators for more complex workflows. Understanding how to use &
effectively is crucial for efficient multitasking and process management in the Shell.
Question: How do you use the sed
command to replace a word in a file?
Answer:
The sed
(Stream Editor) command is widely used in Unix-like systems for text manipulation. It can perform tasks like searching, replacing, inserting, and deleting text in files. To replace a word in a file using sed
, you typically use the s
(substitute) command.
Basic Syntax:
sed 's/old_word/new_word/' filename
old_word
: The word (or pattern) you want to replace.new_word
: The word (or replacement text) that will replaceold_word
.filename
: The name of the file in which you want to perform the replacement.
This command replaces the first occurrence of old_word
with new_word
in each line of the file and outputs the result to the terminal.
Example:
To replace the first occurrence of apple
with orange
in a file named fruits.txt
:
sed 's/apple/orange/' fruits.txt
This will only replace the first occurrence of apple
on each line. The output is displayed on the terminal, but the file itself is not modified unless you specify that it should be updated.
1. Replace all occurrences of a word in a file (globally):
To replace all occurrences of a word in each line, you use the g
flag (global) at the end of the sed
command.
Syntax:
sed 's/old_word/new_word/g' filename
Example:
To replace every occurrence of apple
with orange
in the file fruits.txt
:
sed 's/apple/orange/g' fruits.txt
2. Edit the file in place (modify the original file):
By default, sed
outputs the modified content to the terminal. To actually modify the file, you can use the -i
option (in-place editing). This option will edit the file directly.
Syntax:
sed -i 's/old_word/new_word/g' filename
Example:
To replace all occurrences of apple
with orange
in the file fruits.txt
and save the changes:
sed -i 's/apple/orange/g' fruits.txt
-
Warning: Using
-i
will modify the original file, so you may want to create a backup before using it. You can provide a backup extension to-i
, like-i.bak
, to create a backup of the original file with a.bak
extension:sed -i.bak 's/apple/orange/g' fruits.txt
This will modify
fruits.txt
and create a backup file namedfruits.txt.bak
.
3. Replace a word in a specific line or range of lines:
You can also limit the replacement to specific lines or ranges of lines.
Example: Replace apple
with orange
only on the second line of fruits.txt
:
sed '2s/apple/orange/' fruits.txt
Example: Replace apple
with orange
on lines 2 to 4 of fruits.txt
:
sed '2,4s/apple/orange/' fruits.txt
4. Case-insensitive replacement:
If you want the replacement to be case-insensitive (e.g., replace apple
, Apple
, APPLE
with orange
), you can use the I
flag.
Syntax:
sed 's/old_word/new_word/I' filename
Example:
To replace all occurrences of apple
(case-insensitive) with orange
in fruits.txt
:
sed 's/apple/orange/I' fruits.txt
5. Using Regular Expressions for more complex patterns:
sed
allows the use of regular expressions (regex) for more complex search patterns. For example, to replace any instance of the word apple
or banana
with orange
, you can use a regex pattern.
Example:
sed 's/\(apple\|banana\)/orange/g' fruits.txt
This replaces both apple
and banana
with orange
.
Summary of Common sed
Options:
Option | Description |
---|---|
s/old_word/new_word/ | Basic substitution: replaces the first occurrence of old_word with new_word in each line. |
g | Global flag: replaces all occurrences in each line. |
-i | In-place editing: modifies the original file directly. |
-i.bak | Creates a backup file with the given extension before modifying the original file. |
I | Case-insensitive matching. |
n,m | Specifies a line range (e.g., 2,4 for lines 2 to 4). |
Example Commands:
-
Replace the first occurrence of
apple
withorange
in each line and output the result:sed 's/apple/orange/' fruits.txt
-
Replace all occurrences of
apple
withorange
globally in the file and save the changes:sed -i 's/apple/orange/g' fruits.txt
-
Replace
apple
withorange
only on the first line of the file:sed '1s/apple/orange/' fruits.txt
-
Replace
apple
(case-insensitive) withorange
:sed 's/apple/orange/I' fruits.txt
By using sed
with the appropriate options, you can efficiently replace words in files based on your needs, whether globally or within a specific line or range.
Question: What is the function of the ps
command in Shell?
Answer:
The ps
(Process Status) command in Shell is used to display information about active processes running on a Unix-like system. It provides details such as process IDs (PIDs), the parent process ID (PPID), CPU and memory usage, the status of the process, and the command that started the process.
Basic Syntax:
ps [options]
Common Uses and Examples:
-
Display Processes for the Current User: By default, the
ps
command shows processes running in the current shell session (for the current user) and their basic details.ps
Output example:
PID TTY TIME CMD 1234 pts/0 00:00:00 bash 5678 pts/0 00:00:00 ps
In this example:
PID
: The process ID of the command.TTY
: The terminal associated with the process.TIME
: The amount of CPU time the process has used.CMD
: The name of the command running.
-
Display All Processes (including those from other users): To display all processes running on the system, including those from other users and background processes, use the
-e
or-A
option.ps -e
or
ps -A
Example output:
PID TTY TIME CMD 1 ? 00:00:02 init 1234 pts/0 00:00:00 bash 5678 pts/0 00:00:00 ps
-
Display Processes with Full Details: The
-f
option provides more detailed information about each process, including the parent process ID (PPID) and the user who started the process.ps -f
Example output:
UID PID PPID C STIME TTY TIME CMD user 1234 5678 0 10:00 pts/0 00:00:00 bash user 5678 1234 0 10:01 pts/0 00:00:00 ps
UID
: The user ID of the process owner.PID
: The process ID.PPID
: The parent process ID.C
: CPU usage (as a percentage).STIME
: Start time of the process.TTY
: The terminal associated with the process.TIME
: The total CPU time used by the process.CMD
: The command that initiated the process.
-
Display Processes by User: The
-u
option allows you to display processes for a specific user.ps -u username
Example:
ps -u root
This will list processes that belong to the user
root
. -
Show Hierarchy of Processes (Tree View): To view the process tree and see the parent-child relationships between processes, you can use the
--forest
option along withps
.ps aux --forest
This will display the process tree, showing how processes are related (which processes are parents and which are children).
-
Show Processes with Resource Usage: The
aux
options are commonly used together to show all processes with detailed information, including CPU and memory usage.ps aux
Example output:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND user 1234 0.3 0.1 12345 6789 pts/0 Ss 10:00 0:01 bash user 5678 0.0 0.0 12345 6789 pts/0 R+ 10:01 0:00 ps
USER
: The user running the process.PID
: The process ID.%CPU
: The percentage of CPU usage.%MEM
: The percentage of memory usage.VSZ
: Virtual memory size.RSS
: Resident Set Size (the portion of memory occupied by the process).TTY
: The terminal associated with the process.STAT
: The status of the process (e.g., running, sleeping, etc.).START
: The time when the process started.TIME
: The total CPU time the process has used.COMMAND
: The command used to start the process.
-
Show Process with Specific PID: If you want to display detailed information about a specific process, you can use the
-p
option followed by the process ID (PID).ps -p 1234
This will show details of the process with PID
1234
. -
Display Processes with Custom Format: You can use the
-o
option to specify custom output formats, which allows you to filter the information you want to display.ps -e -o pid,cmd,%cpu,%mem
This will display the process ID (
pid
), the command (cmd
), the CPU usage (%cpu
), and memory usage (%mem
) of all running processes.
Summary of Common ps
Options:
Option | Description |
---|---|
ps | Displays processes running in the current shell session. |
ps -e or ps -A | Displays all processes running on the system. |
ps -f | Displays detailed process information (including PPID). |
ps -u username | Displays processes for a specific user. |
ps aux | Displays detailed process information with resource usage. |
ps -p PID | Displays information for a specific process by PID. |
ps --forest | Displays processes in a tree (hierarchical) view. |
ps -o | Customizes the output format. |
Example Commands:
-
List all processes running on the system:
ps -e
-
Display all processes for the current user:
ps -u username
-
Display processes with detailed resource usage (CPU and memory):
ps aux
-
Show process tree for all processes:
ps aux --forest
-
Show detailed information for a specific process (PID 1234):
ps -p 1234
-
List processes with custom fields (PID, CMD, CPU, MEM):
ps -e -o pid,cmd,%cpu,%mem
Conclusion:
The ps
command is an essential tool for monitoring and managing processes on a Unix-like system. It provides valuable information about running processes, including resource usage, process IDs, and the status of each process. By using the various options with ps
, you can tailor the output to your specific needs, whether you want detailed information about specific processes or a complete overview of all system activities.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as shell interview questions, shell interview experiences, and details about various shell job positions. Click here to check it out.
Tags
- Shell scripting
- Bash
- Sh
- Shell commands
- File manipulation
- Grep
- Awk
- Sed
- Find command
- Ps command
- Chmod
- Stdout
- Stderr
- Error handling
- File redirection
- For loop
- Line by line file reading
- Cron jobs
- Environment variables
- Symbolic links
- Hard links
- Script arguments
- Pipeline
- Shell scripting best practices
- Linux commands
- System administration
- Command line tools