Top 10 Bash + UNIX Interview Questions and Answers

Hello guys, bash is a wonderful command line tool which can be used to automate trivial task. I have written cleanup scripts, start and stop scripts and even schedule jobs using bash and crontab command. Since bash is super useful for anyone running their application in Linux its also a key skill for developers and IT support. Because of that you will always find a couple of questions related to bash on developer interviews. In the past, I have shared Linux interview questions and today I am going to share a couple of bash interview questions which is asked to me throughout the years. If you have worked in bash shell then you can easily answer these questions but if you find it trouble, maybe it's time to revise your bash concepts. 


10 Bash and UNIX Interview Questions for Developers

Without any further ado, here is a list of common bash interview questions which was asked to me on Java developer interviews. These questions are useful for any developer because bash is not related to Java, its just that most of Java applications runs on Linux and UNIX based machines hence knowledge of bash is super useful. 


1) How do you enter a bash shell in UNIX?

by typing bash in command prompt as shown below

user@hostname:~$ bash
user@hostname:~$ 


2) What is #! in a bash script file?
The #! is called sha-bang, which you put at the head of any script, not just bash script, which tells the command interpreter that this file contains set of commands for a particular shell. For a bash script file it should be

#! /bin/bash

#! can be omitted if the script consists only of a set of generic system command and no internal shell directives.

Here is an example of simple bash scripts to put files into trash:

TOp 10 Bash Shell Scripting Interview Questions and Answers

  


3) How do you write for loop in bash script?

In Bash scripting, you can use the for loop to iterate over a sequence of values. There are a few different ways to use the for loop, but a common syntax is as follows:

#!/bin/bash

# Example 1: Iterate over a sequence of numbers
for i in {1..5}
do
  echo "Number: $i"
done

# Example 2: Iterate over items in an array
fruits=("Apple" "Orange" "Banana" "Grapes")
for fruit in "${fruits[@]}"
do
  echo "Fruit: $fruit"
done

In the first example, the loop iterates over a sequence of numbers from 1 to 5. In the second example, the loop iterates over items in an array of fruits. You can adapt the loop to your specific use case by modifying the sequence or array accordingly.

Remember to make your Bash script executable by running chmod +x yourscript.sh if needed.


4) How do you write if else statement in bash script?

In Bash scripting, the if-else statement allows you to conditionally execute blocks of code. The basic syntax is as follows:

#!/bin/bash

# Example 1: Check if a condition is true
if [ condition ]; then
  # Code to be executed if the condition is true
  echo "Condition is true."
else
  # Code to be executed if the condition is false
  echo "Condition is false."
fi

# Example 2: Check the exit status of a command
if command; then
  # Code to be executed if the command is successful (exit status 0)
  echo "Command was successful."
else
  # Code to be executed if the command fails (non-zero exit status)
  echo "Command failed."
fi
You can replace [ condition ] with the actual condition you want to check. You can use various operators such as -eq (equal), -ne (not equal), -lt (less than), -le (less than or equal), -gt (greater than), -ge (greater than or equal), and more.

Remember to terminate the if and else blocks with fi. You can also have multiple elif (else if) blocks to check multiple conditions.

Here's a more concrete example:

#!/bin/bash

# Check if a number is even or odd
number=7

if [ $((number % 2)) -eq 0 ]; then
  echo "$number is even."
else
  echo "$number is odd."
fi

This script checks if the variable number is even or odd using the modulo operator (%).


5) How do you get the user input in a bash shell script?

In Bash scripts, you can use the read command to get user input. Here's a simple example:

#!/bin/bash

# Prompt the user for input
echo "Enter your name: "
read username

# Display the user input
echo "Hello, $username! Welcome to the script."
In this script:

  1. The echo command is used to display a prompt asking the user to enter their name.
  2. The read command is used to read the user's input and store it in the variable username.
  3. The script then uses echo again to display a welcome message using the input provided by the user.
You can use the value stored in the variable $username throughout your script as needed.

Additionally, you can use the -p option with read to combine the prompt and input in a single line:

#!/bin/bash

# Prompt the user for input in a single line
read -p "Enter your name: " username

# Display the user input
echo "Hello, $username! Welcome to the script."
This can make your script more concise when obtaining user input.



6) How do you check the status of last command executed in bash script?
In a Bash script, you can check the exit status of the last command executed using the special variable $?. The exit status is a numerical value that indicates the success or failure of the most recently executed command. A zero exit status typically signifies success, while a non-zero exit status indicates an error.

Here's an example:

#!/bin/bash

# Run a command that may succeed or fail
ls /nonexistent_directory

# Check the exit status
if [ $? -eq 0 ]; then
  echo "Command was successful."
else
  echo "Command failed."
fi

In this example:
  1. The ls /nonexistent_directory command attempts to list the contents of a directory that doesn't exist.
  2. The $? variable is used to check the exit status of the last command.
  3. The script then uses an if statement to determine whether the command was successful or failed, and it prints an appropriate message.
You can also use the exit status directly in conditional statements. For instance:

#!/bin/bash

# Run a command that may succeed or fail
ls /nonexistent_directory

# Use the exit status in a conditional statement
if ls_status=$?; then
  echo "Command was successful. Exit status: $ls_status"
else
  echo "Command failed. Exit status: $ls_status"
fi
In this example, the exit status is stored in the variable ls_status and then used in the conditional statement. This way, you can reference the exit status later in your script if needed.


7) How do you initialize array in bash script?
You can initialize an array in Bash using either of these methods:
# Method 1: Using parentheses
my_array=(value1 value2 value3)

# Method 2: Using the 'declare' command
declare -a my_array=("value1" "value2" "value3")

Just replace value1, value2, etc., with the actual values you want in the array.


8) How do you find if a bash script run successfully?
In Bash, you can check if a script or command ran successfully by examining its exit status. A successful execution typically has an exit status of 0. You can use this information in an if statement to determine success or failure. 

Here's a simple example

#!/bin/bash

# Run a command
ls /some/directory

# Check the exit status
if [ $? -eq 0 ]; then
  echo "Command ran successfully."
else
  echo "Command failed."
fi
In this example:
  1. The ls /some/directory command is executed.
  2. The $? variable is used to check the exit status of the last command.
  3. The script then uses an if statement to determine whether the command ran successfully or failed, and it prints an appropriate message.
You can replace the ls /some/directory command with the actual command or script you want to check for success.


9) What is difference between .bashrc and base_profile in Linux?
While both .bashrc and .bash_profile are hidden files in Linux that users can edit to customize their shell environment. However, they differ in when they are executed:

.bashrc
This file is executed every time you open a new terminal window, regardless of whether it's a login shell or not. This means any changes you make to .bashrc will take effect immediately in the new terminal window. It's commonly used for settings that affect individual shell sessions, like customizing the prompt, defining aliases, or setting non-critical environment variables.

.bash_profile
This file is executed only once, when you log in to your account. This includes logging in locally or remotely via SSH. Any changes you make to .bash_profile won't take effect until you log out and log back in again. 

It's typically used for configurations that need to be available throughout your entire login session, like setting critical environment variables or running commands you want to execute upon login.


Here's a table summarizing the key differences:

What is difference between .bashrc and base_profile in Linux?


In short, you should use .bashrc for personal customizations within each terminal window, and use .bash_profile for system-wide settings that apply throughout your login session.


10) what is difference sh and bash ?
If you don't know, sh and bash are both command interpreters (shells) used in Unix-like operating systems, but there are some key differences:

Standard Compliance:
sh is a standard command interpreter that follows the POSIX (Portable Operating System Interface) standard. It provides a basic set of features defined by the standard. On the other hand, bash (Bourne Again SHell) is an extended version of sh and includes additional features beyond the POSIX standard. It maintains compatibility with sh but introduces new functionalities.

Features:
bash supports a broader set of features, including advanced scripting capabilities, interactive command-line editing, and improved job control. It includes features not found in the basic sh, such as arrays, associative arrays, and more advanced parameter expansion.

Compatibility:
On many Unix-like systems, /bin/sh is a symbolic link or a hard link to another shell, typically bash or a more lightweight shell like dash. This means that using sh may actually invoke a different shell, depending on the system.

Performance:
sh is often used for scripts that aim for better portability across different Unix systems. It may be preferred in situations where adherence to the POSIX standard is crucial and advanced features of bash are not required.

bash is a more feature-rich shell but may have a slightly higher resource footprint compared to simpler shells. It is commonly used for interactive command-line sessions and more complex scripting tasks.

Here is a nice table highlighting the difference between sh and bash in Linux. This table highlights key differences in standard compliance, features, compatibility, and common use cases between sh and bash

what is difference sh and bash ?


In summary, bash is an extended version of sh with additional features and improvements. The choice between them depends on the specific requirements of your scripts or interactive shell sessions and the desired level of compatibility across different Unix-like systems.


That's all about bash shell scripting interview questions for Linux and UNIX developers. I have seen bash related questions on developer interviews, particularly Java developer and I strongly recommend every Java developer and IT professional to learn bash. It's one of the most popular shell and it pays to learn and know about it. If you have any other bash related questions which was asked to you on interviews, feel free to share here, I will try to answer. 


1 comment:

  1. I was asked what will happen if you export environment variable in a bash script? will it be available after your script is finished? Do you know the answer of this question?

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.