Most Frequently asked shell Interview Questions

author image Hirely
at 02 Jan, 2025

Question: What is the difference between > and >> in Shell scripting?

Answer:

In Shell scripting, > and >> are both used for redirecting output to files, but they behave differently:

  • > (Single Greater-than sign):

    • The > operator is used to overwrite a file with new content.
    • If the file already exists, it will be replaced with the new output.
    • If the file does not exist, it will be created.
    • Example:
      echo "Hello, World!" > file.txt
      This will create (or overwrite if it already exists) file.txt with the text “Hello, World!”.
  • >> (Double Greater-than sign):

    • The >> operator is used to append output to the end of a file.
    • If the file does not exist, it will be created.
    • If the file already exists, the new content will be added at the end of the file without removing the existing content.
    • Example:
      echo "New line" >> file.txt
      This will append “New line” to the end of file.txt without affecting its previous content.

In summary:

  • > overwrites the file with new content.
  • >> appends new content to the end of the file.

Question: How would you write a Shell script to print the number of lines in a file?

Answer:

To write a Shell script that prints the number of lines in a file, you can use the wc (word count) command with the -l option, which counts the number of lines in a file.

Here is an example Shell script:

#!/bin/bash

# Check if a filename is provided as an argument
if [ -z "$1" ]; then
    echo "Please provide a file name as an argument."
    exit 1
fi

# Use wc -l to count the lines in the provided file
line_count=$(wc -l < "$1")

# Print the number of lines
echo "The number of lines in the file '$1' is: $line_count"

Explanation:

  1. #!/bin/bash: This is the shebang line, which specifies the interpreter to use for executing the script (in this case, Bash).
  2. if [ -z "$1" ]; then: This checks if a filename argument is provided. If not, the script will prompt the user to provide one.
  3. wc -l < "$1": The wc -l command counts the number of lines in the file. The < "$1" redirects the file as input to wc, which prevents the filename from being included in the output.
  4. echo: Finally, the script prints the number of lines in the file.

Example usage:

$ ./count_lines.sh myfile.txt
The number of lines in the file 'myfile.txt' is: 42

This script will count the lines in myfile.txt and print the result.

Question: What are the differences between bash and sh?

Answer:

bash (Bourne Again Shell) and sh (Bourne Shell) are both command-line interpreters, but they have key differences in terms of features, behavior, and functionality. Here are the main differences:

1. History and Origins:

  • sh (Bourne Shell):
    • Developed by Stephen Bourne in 1977 as the original Unix shell.
    • It was the default shell for many Unix systems before more advanced shells like bash emerged.
  • bash (Bourne Again Shell):
    • Developed by Brian Fox for the GNU Project in 1987 as a free software replacement for the Bourne Shell.
    • It is backward-compatible with sh, but offers many more features and enhancements.

2. Compatibility:

  • sh: Refers to the Bourne Shell, which is a more basic, minimalist shell.
  • bash: While bash is compatible with sh (it can execute sh-style scripts), it offers many additional features not available in sh.

3. Features:

  • bash provides the following additional features that sh does not have:
    • Command-line editing: You can use the arrow keys to navigate through the command history in bash, while sh does not support this.
    • Command substitution: bash supports more advanced ways to perform command substitution, such as $(command) (which is more readable than the old-style backticks `command` used in sh).
    • Arrays: bash supports arrays, allowing the user to store multiple values in variables, unlike sh, which only supports scalar variables.
    • Brace expansion: bash supports brace expansion ({a,b,c}), which generates combinations of the elements inside the braces.
    • Extended pattern matching: bash has advanced pattern matching features, such as globstar (**) for recursive globbing.
    • Improved scripting features: bash supports more advanced features for script writing, such as [[ ... ]] for conditional expressions (which is more powerful and flexible than [ in sh).
    • Job control: bash allows better job control, such as background processes (&), and managing processes (fg, bg, jobs).

4. Scripting Syntax:

  • Both bash and sh use a similar syntax for basic scripting (e.g., loops, conditionals, functions), but bash offers more advanced syntactical constructs.
  • bash scripts often take advantage of its extended features, such as arrays and functions with more flexible syntax.

5. Performance:

  • sh is typically faster than bash in simple script execution because it is a lighter, more basic shell with fewer features.
  • bash has a more feature-rich environment, so it may have a slightly slower startup time, but the difference is usually negligible for most tasks.

6. Portability:

  • sh is considered more portable because it is universally available on Unix-like systems (including older versions of Unix). If you’re writing a script that needs to run on a wide range of systems, you might use sh for better compatibility.
  • bash is widely available on modern Linux distributions and other systems, but it is not universally guaranteed (for example, some minimal environments may not have bash installed by default). Therefore, bash scripts may not run on systems that only support sh.

7. Exit Status:

  • sh has a simpler approach to exit statuses, where non-zero exit codes typically indicate failure.
  • bash can provide more detailed exit statuses in advanced scripting scenarios, such as with the use of set -e to make scripts exit immediately on any error.

8. Shell Invocation:

  • When you invoke a shell with sh, it could be an actual Bourne Shell or a symlink to another shell, like bash, depending on the system configuration.
  • bash is typically invoked specifically as bash or through the shebang #!/bin/bash at the top of a script.

9. Error Handling:

  • bash has more powerful error handling mechanisms like trap for catching signals and errors, whereas sh has more basic error-handling capabilities.

Summary:

  • sh is the original Unix shell, minimal and highly portable, but with fewer advanced features.
  • bash is an enhanced version of the Bourne Shell, offering a wide range of features such as command-line editing, arrays, improved conditionals, and better error handling. However, it may not be as universally available as sh.

In most modern environments, bash is used due to its greater functionality, but if you’re writing scripts intended to run on a variety of systems, it’s safer to stick to the features supported by sh for maximum portability.

Question: How can you pass arguments to a Shell script?

Answer:

In Shell scripting, you can pass arguments to a script when executing it from the command line. These arguments can be accessed within the script using special variables. Here’s how it works:

1. Passing Arguments:

You pass arguments to a Shell script by typing them after the script’s name in the command line. For example:

$ ./script.sh arg1 arg2 arg3

In this example, arg1, arg2, and arg3 are passed as arguments to script.sh.

2. Accessing Arguments in the Script:

Within the script, you can refer to these arguments using positional parameters. Here are the key variables used to access arguments:

  • $1: Refers to the first argument (arg1 in the example above).
  • $2: Refers to the second argument (arg2).
  • $3: Refers to the third argument (arg3).
  • $#: Refers to the number of arguments passed to the script.
  • $@: Refers to all arguments passed to the script (as individual items).
  • $*: Also refers to all arguments, but treats them as a single string (with spaces between arguments).
  • $0: Refers to the name of the script itself.

Example Script:

#!/bin/bash

# Print the script name
echo "Script name: $0"

# Print the first argument
echo "First argument: $1"

# Print the second argument
echo "Second argument: $2"

# Print the number of arguments
echo "Number of arguments: $#"

# Print all arguments as a list
echo "All arguments: $@"

# Print all arguments as a single string
echo "All arguments as a single string: $*"

3. Running the Script:

When you run the script with arguments, it might look like this:

$ ./script.sh arg1 arg2 arg3
Script name: ./script.sh
First argument: arg1
Second argument: arg2
Number of arguments: 3
All arguments: arg1 arg2 arg3
All arguments as a single string: arg1 arg2 arg3

4. Using a Loop to Process Multiple Arguments:

If you want to loop over all arguments passed to the script, you can use a for loop like this:

#!/bin/bash

# Loop over all arguments
for arg in "$@"; do
  echo "Argument: $arg"
done

5. Example: Checking if Arguments Are Passed:

You can also check whether any arguments were passed and take appropriate action:

#!/bin/bash

# Check if at least one argument was provided
if [ $# -eq 0 ]; then
  echo "No arguments provided"
  exit 1
fi

# Print the arguments
echo "Arguments passed: $@"

Summary:

  • You pass arguments to a Shell script by including them after the script name in the command line.
  • Inside the script, use $1, $2, etc., to access individual arguments, $@ or $* to access all arguments, and $# to get the number of arguments.
  • You can also loop over arguments to process them or check if arguments were passed using conditional statements.

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.

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now