2023 Top Interview Questions for Shell Scripting - IQCode

Introduction to Shell Scripting

Shell scripting refers to creating a text file that contains a sequence of commands which can be executed by the shell. This eliminates the need for repetitive work and saves time, making it the easiest programming language to use for system-level operations. The most common reason for using shell scripting is programming operating systems of Windows, UNIX, and Apple. Also, companies use this script to develop an operating system with their own features.

In addition to this, shell scripts can be used for various applications, such as automation of code compiling process, running a program, or creating an environment for programming, completing batch processing, and file manipulation, integrating existing programs, performing routine backups, keeping an eye on a system, system administration tasks, and creating, maintaining, and implementing system boot scripts.

Below is an example of a shell script:


#!/bin/bash
echo "Hello World"

To run the above code, execute it as follows:

$ bash hello.sh

It will print

Hello World

.

If you are a fresher and are preparing for a shell scripting interview, below is a sample question to help you:

1. What is a shell?

Why is a shell script necessary?

Shell scripting is needed in order to automate tasks and provide a way to execute commands and programs by creating sequences of commands in a shell environment. It saves time and helps with consistency in executing tasks. Shell scripts can also be used to manipulate files, install software, run database queries, and perform various other system tasks.


#Example
#!/bin/bash
# This script will ask the user for their name and age and then print out a greeting
echo "What is your name?"
read name
echo "How old are you?"
read age
echo "Hello, $name! You are $age years old."


Advantages of Shell Scripting

Shell scripting has several advantages:

  • Automates repetitive tasks and saves time
  • Allows for fast prototyping and creates easy-to-use interfaces for complex tasks
  • Provides easy access to system resources and can execute system commands
  • Offers a simple and portable way to perform system administration tasks across multiple platforms
  • Debugging shell scripts is easier compared to programming languages like C or Java
  • Scripting languages like Bash are open source and can be easily customized to suit specific requirements
 # This is a sample shell script
#!/bin/bash
# This script will display the directories in the current working directory

echo "Directories in the current working directory are:"
ls -d */     # display only the directories


Limitations of Shell Scripting

1. Limited Portability: Shell scripts are not very portable across different operating systems, as different systems may have different shell languages and capabilities.

2. Limited Power: Compared to high-level programming languages such as Python or Java, shell scripts have limited power and cannot handle complex tasks as efficiently.

3. Slow Speed: Shell scripts are generally slower because they are interpreted rather than compiled, which can cause performance issues for large or complex scripts.

4. Poor Debugging Support: Debugging shell scripts is often difficult, as error messages can be cryptic and there is little support for debugging tools or integrated development environments (IDEs).

5. Limited Scalability: Shell scripts can become unwieldy and difficult to maintain as they grow in size and complexity, making them less scalable for large projects.

6. Limited Security: Shell scripts can pose a security risk if not written carefully, as they can be vulnerable to injection attacks or other types of security exploits.

Naming the file for storing shell programs.

In Unix-like operating systems, shell programs are typically stored in a file with the extension ".sh". This file is referred to as a shell script or a bash script, depending on the type of shell being used. The file can be executed by typing its name in the command line or by using the "chmod" command to make it executable and then running it like any other program. Storing shell programs in a separate file allows for easy editing and sharing of scripts among users.

Types of Shells Available

There are several types of shells available in the command-line interface. Some commonly used ones are:

1. Bash (Bourne-Again SHell)

2. C Shell (C SHell)

3. Korn Shell (KSH)

4. Z Shell (ZSH)

H3 tag: Difference between Bourne Shell and C Shell

The Bourne shell (sh) and C shell (csh) are both command line shells used in Unix-based operating systems. Here are the differences between the two:

1. Syntax: The Bourne shell uses a syntax that is more consistent and easier to understand, while the C shell has a more complex and varied syntax.

2. Variables: The Bourne shell uses a simple variable syntax with no distinction between environment variables and shell variables, while the C shell has distinct environment and shell variables.

3. History: The Bourne shell has a limited command history feature, while the C shell has a more powerful history feature that includes the ability to recall commands by specifying their first few letters.

4. Scripting: The Bourne shell is better suited for scripting and automation tasks, while the C shell is better for interactive use and smaller scripts.

5. Script Execution: The Bourne shell reads a script and executes it, while the C shell reads the entire script before executing it. This means that the Bourne shell can execute scripts more quickly.

Overall, the choice between the two shells depends on personal preference and the specific use case.

What is a Shell Variable?

In the context of Unix-like operating systems, a shell variable is a variable defined and used within a shell (command-line interpreter), such as Bash or Zsh. Shell variables are used to store values that can be accessed and manipulated by the shell, scripts, and programs that run within the shell environment. Syntax for defining a shell variable is variable_name=value.

Types of Variables Commonly Used in Shell Scripting

In shell scripting, there are primarily three types of variables:

1. Local Variables:

These variables are defined and used within a shell function. They are not accessible outside the function.

2. Environment Variables:

These are system-wide variables that can be accessed by any process or program that runs on the system. Examples include PATH, HOME, and SHELL.

3. Shell Variables:

These variables are defined and maintained by the shell. They can be accessed and modified using shell commands. Examples include USER, UID, and RANDOM.

Explanation of Positional Parameters

Positional parameters refer to the variables that are used to pass arguments or inputs to a script or function in a specific order. The position of the argument passed as a parameter corresponds to the position of the parameter in the function or script definition.

For instance, if a function is defined with two positional parameters, the first parameter will correspond to the first argument passed to the function, and the second parameter will correspond to the second argument passed to it.

Positional parameters are commonly used in command-line interfaces, where users can pass different values to a program by changing the order of their inputs. In Bash scripting, positional parameters are denoted by the variables $1, $2, $3, and so on, for the first, second, and third parameters, respectively.

Using positional parameters can make code more readable and easier to maintain, as it eliminates the need to pass individual parameters to a function or script manually and reduces the chances of errors and bugs.

Control Instructions in Programming

In programming, control instructions refer to statements or commands that dictate the flow of execution in a program. These instructions are used to control the behavior of the program and to make decisions based on certain conditions. Some examples of control instructions include "if-else" statements, "for" and "while" loops, and "switch-case" statements. By using these control instructions, programmers can create programs that perform complex tasks and respond to different inputs in a flexible and efficient manner.

Types of Control Instructions in a Shell

In a shell, there are two types of control instructions:

1.

Flow Control Instructions

: These are used for controlling the flow of a shell script. The most commonly used flow control instructions are

if

, the

for

loop, the

while

loop and the

case

statement.

2.

Exit Control Instructions

: These are used for controlling the execution of a shell script. The most commonly used exit control instruction is the

exit

command, which is used to terminate a script. Other exit control instructions include the

return

command and the

break

command, which are used within loops and functions.

Understanding the different types of control instructions is crucial for writing effective and efficient shell scripts.

Ways to Create Shortcuts in Linux

Creating shortcuts in Linux can improve your productivity and save time. Here are some ways to create shortcuts:

1. Desktop Shortcuts: 
  • Right-click on the desktop and select "Create Launcher" or "Create Shortcut".
  • Fill in the required information, such as name, command, and icon.
  • Click "OK" to create the shortcut on the desktop.
2. Keyboard Shortcuts: 
  • Open the "Keyboard" settings from the system menu.
  • Select the "Shortcuts" tab.
  • Click on the "+" button to add a new shortcut.
  • Fill in the required information, such as name and command.
  • Assign a key combination to the shortcut.
  • Click "Add" to create the shortcut.
3. Alias Shortcuts:
  • Create an alias for a command using the following syntax:
    alias aliasname='command'
  • Add the alias to your bashrc file to make it permanent:
    echo "aliasname='command'" >> ~/.bashrc
  • Reload bashrc with the command:
    source ~/.bashrc

By using these methods, you can easily create shortcuts in Linux and simplify your workflow.

How to Determine if a Link is a Hard Link or Soft Link

You can determine if a link is a hard link or soft link by using the "ls" command in a terminal window.

A hard link is a direct link to an inode on a file system, while a soft link, also known as a symbolic link, points to another file or directory by name.

To check if a link is a hard link, use the command:

ls -li filename

This will display the inode number of the file. If the inode number is the same for both the original file and the linked file, then it is a hard link.

To check if a link is a symbolic link, use the command:

ls -l filename

This will display the file details, including the link information. If the file is a symbolic link, the link information will be displayed as the file/directory path it points to.

Difference between Hard Link and Soft Link

In Linux, both hard links and soft links are used to create references to files or directories. However, there are some important differences between the two:

  • A hard link creates an exact duplicate of the original file, while a soft link creates a new file that points to the original file.
  • Deleting the original file will not affect a hard link, but will render a soft link useless.
  • Changing the name of the original file will not affect a hard link, but will render a soft link useless.
  • A hard link can only be created for files that are stored on the same file system, while a soft link can be created for files on different file systems.

Overall, hard links are more robust than soft links, but soft links offer more flexibility.


// example of creating a hard link
ln oldfile newfile

// example of creating a soft link
ln -s oldfile newfile

What is GUI Scripting?

GUI scripting refers to the process of automating the interactions with a graphical user interface (GUI) using a scripting language. The scripting language is used to write code that simulates user actions such as clicking buttons, typing text, selecting options, and more. This is commonly used in software testing, where automated GUI tests can be run to verify the functionality of an application. GUI scripting can also be used for automating repetitive tasks on a computer, making it a valuable tool for productivity.

Explanation of Shebang Line in Shell Scripting

In shell scripting, the shebang line refers to the first line of the script that begins with a hash (#) symbol and an exclamation point (!). It is also known as a hashbang, sharpbang, or pound bang.

The purpose of the shebang line is to indicate the interpreter that should be used to execute the script. For example, if the script uses the Bash shell, the shebang line would be:

#!/bin/bash

The shebang line is important because it allows the script to be executed by simply typing its name, rather than needing to specify the interpreter each time. It also ensures that the script is executed with the correct interpreter, as different shells may have different syntax and commands.

In summary, the shebang line is a crucial component of shell scripting as it tells the system which interpreter to use for executing the script.

What is a File System? Components of a Linux File System

A file system is a way of organizing and storing files on a computer. It includes everything from how files are named and accessed to the physical layout of the storage device. In Linux, a file system is comprised of four core components:

1. Superblock: The superblock is a data structure that contains important information about the file system, such as its size, status, and layout. It is the first block of data on the storage device and serves as the entry point to the file system.

2. Inode: An inode is a data structure that stores information about a file or directory, including its owner, permissions, and location on the disk. Each file or directory has a unique inode number.

3. Data Block: A data block is a chunk of space on the disk that is used to store the contents of files. The size of each data block can differ depending on the file system.

4. Directory: A directory is a type of file that contains a list of files and subdirectories stored in that directory. Directories are used to organize files and make it easier to navigate the file system.H3 tag: Alternative Command for Echo

The alternative command for echo in a Windows command prompt is "echo.” However, in Unix-based systems such as Mac or Linux, the alternative command is "printf." These commands perform similar functions of displaying text on the command line interface.

Connecting to a Database Server

To connect to a database server, you can follow these steps:

1. Identify the type of database management system (DBMS) you are connecting to (e.g., MySQL, Oracle, PostgreSQL). 2. Install the appropriate database driver or client software for that DBMS. 3. Obtain the necessary credentials (e.g., username and password) to access the database server. 4. Use programming language-specific code to establish a connection with the database server using the driver or client software and the credentials. 5. Once connected, you can perform operations on the database, such as querying and updating data.

Here's an example in Python using the MySQL driver:


import mysql.connector

# establish database connection
cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='mydatabase')

# execute a query
cursor = cnx.cursor()
query = "SELECT * FROM mytable"
cursor.execute(query)

# process query results
for result in cursor:
   print(result)

# close connection
cnx.close()

Note that the specific details for connecting to a database server may vary depending on the DBMS and programming language being used. It's always a good idea to consult the documentation for the specific tools you are working with and to follow best practices for security and performance.

Understanding the Importance of $#

In programming, $# is a special variable that represents the number of arguments passed to a Unix shell script. This variable is particularly important because it allows developers to write scripts that can handle a variable number of inputs.

For example, if a script requires two file names as inputs, the developer can use $# to ensure that the correct number of arguments are passed to the script. If the user passes only one argument, the script will return an error message.

In addition to ensuring that the correct number of arguments are passed, $# can also be used to create flexible scripts that can perform a variety of tasks based on the number of inputs provided.

In summary, understanding the importance of $# can help developers write more flexible and robust shell scripts that can handle a wide range of inputs.To execute a shell file, use the following command:


./file_name.sh

Replace "file_name.sh" with the actual name of the shell file you want to execute. You must be in the directory where the file is located or provide the full path to the file if it's located elsewhere.Command to find out the number of arguments passed to the script: Code:

bash
echo $#

This command will output the number of arguments passed to the script. The symbol $# is a special variable in Bash that holds the number of arguments passed to the script.

How long does a variable in a shell script last?

In general, a variable in a shell script lasts throughout the execution of the script. However, there are some cases in which a variable might have a limited lifespan. For example, if the script is run as a subshell, any variables created within that subshell will not be accessible outside of it. Additionally, if a variable is unset or overwritten within the script, its previous value will no longer be available.


  # Example of a shell script variable
  my_variable="Hello, world!"
  echo $my_variable

In this example, the variable "my_variable" will be accessible throughout the execution of the script.

H3 tag: The dot at the beginning of a file name

In Unix-based systems, the dot at the beginning of a file name indicates that the file is a hidden file. These files are not visible when using normal directory listings.

To list hidden files in a Unix-based system, you can use the command "ls -a" which will show all files, including hidden ones.

Explanation of the "$?" command

In the Linux or Unix operating systems, the "$?" command is used to check the exit status of the previously executed command. The exit status is a numerical value that represents whether the execution of the command was successful or not.

If the value of "$?" is 0, it means that the command was executed successfully. If the value of "$?" is non-zero, it indicates that the command encountered an error during execution.

This command is useful in shell scripting and automation, where the success or failure of a command needs to be checked before proceeding with the next step.

Best way to run a script in the background

To run a script in the background, you can use the "&" operator at the end of the command. For example:

python my_script.py &

This will run the script in the background, allowing you to continue using the terminal for other tasks. Another option is to use the "nohup" command, which allows the script to keep running even if you close the terminal. For example:

nohup python my_script.py &

You can also use a tool like "screen" to run the script in a separate terminal session, which allows you to disconnect from the session and reconnect later to check on the progress of the script. To use screen, first start a new session with the command:

screen

Then run your script as usual within the session. To detach from the session at any time, press "Ctrl-a d". You can then reconnect to the session later with the command:

screen -r


Shell Scripting Interview Questions for Experienced

Question 28: Can you explain what Crontab is?

Crontab

is a Unix command used to schedule commands or scripts to run automatically at specified times and dates. The user specifies a crontab file and adds an entry for each command they want to run. Each entry contains a schedule and a command to run. Crontab is commonly used for repetitive tasks such as backup scripts, maintenance tasks, or scheduled data processing.

Two Files Used with Crontab Command

The crontab command in Linux and Unix-based systems refers to a file that contains a list of commands that need to be executed periodically according to a predefined schedule. There are two main files associated with the crontab command:

1. System-wide crontab file: This is the file that contains the system-wide crontab entries. It is usually located in the directory /etc/crontab and is edited by the system administrator.

2. User-specific crontab file: This is the file that contains the crontab entries for a specific user. Each user can have their own crontab file, which is edited using the crontab command followed by the -e option.

To list the contents of the system-wide crontab file, you can use the following command:


cat /etc/crontab

To list the contents of a user-specific crontab file, you can use the following command:


crontab -l

These commands will display the crontab entries in the respective files.

Command to take backup

The command used to take a backup may vary depending on the specific system or software being used. In general, common commands for taking backups on a Unix/Linux system include "tar" and "cpio". On Windows systems, the built-in "backup and restore" utility can be used, or third-party software such as "Acronis True Image" or "Backup Exec". The specific syntax and options for these commands will depend on the system and the desired backup configuration.H3 tag: Difference between $* and $@

In Bash scripting, both `$*` and `$@` are special parameters that expand into all the positional parameters passed to the script. However, they differ in how they treat whitespace characters and quote characters.

- `$*` expands into a single string that separates each positional parameter with the first character of the IFS (Internal Field Separator) environment variable. By default, this is a space character. This means that `$*` treats all positional parameters as a single argument, regardless of how many there are and whether they contain spaces.

- `$@` expands into multiple separate strings, one for each positional parameter. Each parameter is properly quoted to prevent word splitting and pathname expansion. So, `$@` treats each positional parameter as a separate argument and preserves any whitespace or quoting it contains.

To illustrate the difference, consider the following example:


#!/bin/bash

function print_args() {
  echo "Argument count: $#"
  echo "All arguments as a single string: $*"
  echo "All arguments as separate strings:"
  for arg in "$@"; do
    echo "$arg"
  done
}

print_args "foo bar" baz qux

Output:


Argument count: 3
All arguments as a single string: foo bar baz qux
All arguments as separate strings:
foo bar
baz
qux

As you can see, `$*` combines all positional parameters into a single string, while `$@` preserves the separate arguments.

Command for Comparing Strings in a Shell Script

The command used to compare strings in a shell script is "test" or "[ ]" with the "=" or "!=" operator.

Code:

bash
if [ "$string1" = "$string2" ]; then
    echo "Strings are equal"
else
    echo "Strings are not equal"
fi

In the above code, the "if" statement uses the test command to compare "string1" and "string2" using the "=" operator. If they are equal, the first echo statement is executed, otherwise, the second one is executed.

Loop Syntax in Shell Scripting:

There are four types of loops in shell scripting.

1. For loop: The syntax for the for loop is:


for variable_name in values
do
    commands
done

2. While loop: The syntax for the while loop is:


while [ condition ]
do
    commands
done

3. Until loop: The syntax for the until loop is:


until [ condition ]
do
    commands
done

4. Select loop: The syntax for the select loop is:


select variable_name in values
do
    commands
done

Understanding Interactive and Non-Interactive Shells

In Unix-based operating systems, a shell is a program that provides a command-line interface (CLI) for interacting with the system. The shell can be operated in two different modes: interactive and non-interactive.

An interactive shell allows the user to enter commands that are immediately executed by the system, and the shell displays the output of those commands back to the user. The user can execute multiple commands in a row and interact with the system in real-time.

On the other hand, a non-interactive shell is typically used for running scripts or batches of commands automatically, without the need for user input. Non-interactive shells don't display output to the user, and they terminate as soon as the script or command batch is completed.

Knowing the difference between interactive and non-interactive shells is important for shell scripting and automation tasks. Interactive shells are useful for debugging and testing commands, while non-interactive shells are ideal for running automated processes, such as those used in cron jobs.

Passing and Accessing Arguments in a Linux Script

To pass arguments to a Linux script, you can simply provide them after the script name separated by space, such as:


./myscript.sh arg1 arg2 arg3

In the script, you can access the arguments using the positional parameter variables: `$1` for the first argument, `$2` for the second argument, and so on.

For example, if you want to access the first argument passed to the script, you can use:

bash
#!/bin/bash

echo "The first argument is: $1"

If you want to access all the arguments passed to the script, you can use `$@`, which will expand to all positional parameters. For example:

bash
#!/bin/bash

echo "All arguments: $@"

This will print all arguments passed to the script.

You can also use a loop to iterate over all the arguments, like this:

bash
#!/bin/bash

for arg in "$@"
do
  echo "Processing $arg"
done

This will print each argument passed to the script, one at a time.

Understanding the "S" Permission Bit in a File

The "S" permission bit in a file refers to the Set User ID (SUID) and Set Group ID (SGID) bits. When the SUID bit is set, an executable file runs with the permissions of the file's owner instead of the user who is running the file. Similarly, when the SGID bit is set, a file is executed with the group permissions of the file's group owner instead of the user's group permissions. These permission bits are often used for applications that require additional privileges beyond what a standard user would have. It is important to use SUID and SGID bits carefully as improper use may introduce security vulnerabilities.

Debugging a Shell Script

When debugging a shell script, you can use the following techniques:

1. Add the following line to the top of the script to enable debugging mode:

`#!/bin/bash -x`

This will execute the script in debug mode and will print each command before executing it.

2. Use the `set` command to enable certain debug options such as `set -x` to print commands and their arguments as they are executed, or `set -e` to exit immediately if any command exits with a non-zero status.

3. Use the `echo` command to print out variables or the values of variables to see what is happening during the script execution.

4. Use `trap` to catch signals and handle them appropriately.

5. Use `set -u` to exit whenever an undeclared variable is used. This helps to prevent uninitialized variables from causing errors.

6. Use `set -o pipefail` to catch errors when using pipes.

By using these techniques, you can effectively debug your shell script and find and fix any issues that may be occurring.

Best Practices for Debugging Shell Scripts/Programs

Debugging shell scripts/programs can be a tricky process, but following these best practices can help make it easier:

1. Use the -x option to turn on debugging mode.

This option can be added to the top of the shell script, and it will print each command before it is executed, allowing you to see which operations are causing the problem.

2. Check variable values using echo.

You can use the echo command to print variable values at different stages of the script to check if they are being set correctly or not.

3. Comment out sections of the script.

If you suspect that a specific section of the script is causing the problem, you can comment it out and then run the script again. If the script runs without errors after commenting out the section, then you know that the problem is within that section.

4. Use shellcheck.

Shellcheck is a static analysis tool that can be used to identify any syntax errors or common mistakes in shell scripts.

5. Use logging.

You can use logging to keep track of what the script is doing at each stage. This can make it easier to identify where the script is failing.

By following these best practices, you can save time and frustration when debugging shell scripts/programs.

Importance of sed and awk commands

The sed command and awk command are important text manipulation tools in Linux/Unix systems. They allow users to perform various text editing operations on files and streams.

The sed command is a stream editor that can be used to preprocess and transform text. It is often used for the automation of repetitive text-editing tasks. Some common operations that can be performed with sed include search and replace, inserting, editing, and deleting text.

The awk command is a more powerful text processing tool than sed, as it can handle delimited data and perform more complex operations. It is often used for data extraction and reporting tasks. Some of the common use cases for awk include filtering, reformatting, and aggregating data.

Both sed and awk are extremely versatile tools that can be combined with other Linux commands to form powerful text processing pipelines. Understanding these tools is essential for anyone working with large amounts of text data on Linux systems.

Difference between "=" and "==" in programming

In programming, "=" and "==" are two different operators with distinct functions.

The "=" operator is used for assignment, where a value is assigned to a variable. For example, `x = 5` means that the value 5 is assigned to the variable x.

On the other hand, "==" is a comparison operator that is used to compare two values to check if they are equal or not. This operator returns a Boolean value of True or False. For instance, `x == 5` will return True when the value of x is equal to 5 and False otherwise.

It is important to note that mistaking "=" for "==" in a comparison operation can lead to logical errors in the program.Command to display the shell's environment variable in Linux: echo $VARIABLE_NAME

Commands to Check Disk Usage in Linux

Here are some different commands available in Linux to check disk usage:

df

: This command displays the amount of disk space used and available on your file system.

du

: This command estimates file space usage on your file system.

ls

: This command lists files and directories in the current directory.

ncdu

: This command provides a curses-based interface to explore and free up space on your file system.

find

: This command is useful for searching directories and finding files based on their size.

filelight

: This command provides an interactive graphical representation of your file system, making it easier to identify the largest files and directories.

dstat

: This command displays system resource statistics, including disk usage, in real-time.

bmon

: This command is a bandwidth monitor that also displays disk usage statistics.

iotop

: This command displays I/O usage on your system, showing which processes are using the most disk access.

Understanding Metacharacters

Metacharacters are special characters that have a predefined meaning in Regular Expressions. For example, the dot (.) is a metacharacter that represents any character except for a line break. Other common metacharacters include ^, $, *, +, ?, |, [], (), {}, etc. It is important to understand the role of metacharacters when creating Regular Expressions to match specific patterns.

Finding the Total Number of Shells Available in a System

To find the total number of shells available in a system, you can use the following command in a terminal:

Code:


cat /etc/shells | wc -l

This command will display the total number of shells available in the system by counting the number of lines in the `/etc/shells` file. The `/etc/shells` file contains a list of all the available shells in the system.

You can also view the contents of the `/etc/shells` file by using the following command in the terminal:

Code:


cat /etc/shells

This will display the complete list of available shells in the system.

Opening a Read-Only File in UNIX/Shell

To open a file in read-only mode in UNIX/Shell, you can use the "cat" or "less" command followed by the file name. For instance, to open a read-only file named "example.txt," you can use the following syntax:


cat example.txt

This will display the contents of "example.txt" on the screen, allowing you to read it. However, you will not be able to modify or write to the file.

Alternatively, you can use the "less" command to open a read-only file, which will allow you to scroll through the contents of the file using the arrow keys. To open "example.txt" using "less," you can type:


less example.txt

Press the "q" key to exit "less" mode and return to the command prompt.Command to know how long the system has been running:

The command used to display the time period that the system has been running is "uptime". This command provides information about the current time, how long the system has been running, the number of users logged in, and the average load time for the past 1, 5, and 15 minutes.

To use this command, open the terminal or command prompt and type "uptime" followed by pressing the enter key. The output will display the information mentioned above.The symbols "$$" typically denote a display math environment in LaTeX, while "$!" is a negative spacing command that reduces the space between two mathematical expressions.

Difference between grep and find command

grep

and

find

are both popular Unix commands used for searching files and directories, but they have different functionalities. Below are some of the main differences between these two commands:

  • Functionality:
    grep

    is primarily used to search for specific patterns in a text while

    find

    is used to locate files and directories based on specified search criteria.

  • Usage: The basic syntax for
    grep

    command is:

    grep [OPTIONS] PATTERN [FILE]


    Whereas, the basic syntax for

    find

    command is:

    find [path] [expression]


    Here, the

    [OPTIONS]

    with

    grep

    are used to modify the search behavior, whereas the

    [path]

    with

    find

    specifies the starting directory for the search and

    [expression]

    specifies the search criteria.

  • Search criteria: With
    find

    , you can search for files based on various criteria such as name, size, type, permissions, and more. On the other hand,

    grep

    searches for patterns within files based on regular expressions.

  • Output:
    grep

    outputs the lines that contain the pattern you searched for while

    find

    outputs the name of the files or directories that meet the search criteria.

  • Speed:
    grep

    is generally faster than

    find

    because it searches through files directly, whereas

    find

    needs to traverse the directory tree before locating the files.

grep

and

find

have different use cases and it is important to understand their respective functionalities to use them effectively.

Creating a Function in Shell Script

To create a function in a shell script, use the following syntax:


function_name () {
    # Function code goes here
}

Or:


function function_name {
    # Function code goes here
}

For example, if you want to create a function that prints "Hello, World!" to the console, you can do the following:


hello_world () {
    echo "Hello, World!"
}

You can call this function in your script using its name:


# Call hello_world function
hello_world

This will output:


Hello, World!

Remember to define your functions before calling them in your script.

Using Pipe Commands in Linux

The pipe command is used to pass the output of one command as input to another command in Linux. The symbol for the pipe command is ‘|’. Here is an example of how to use pipe commands in Linux:

Code:


command1 | command2

This code passes the output of `command1` to `command2`. This is useful when you want to filter or manipulate the output of a command before passing it to another command.

For example, suppose you want to list all the files in a directory and then count the number of files. You can use the following commands:

Code:


ls | wc -l

This code will display the number of files in the directory.

You can also use multiple pipe commands to filter the output even further:

Code:


ps -ef | grep httpd | awk '{ print $2 }'

This code will display the process IDs (PIDs) of all running httpd processes.

Using pipe commands in Linux can greatly simplify complex tasks by allowing you to chain commands together in a simple, efficient manner.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.