The Ultimate Compilation of Linux Commands Interview Questions and Answers

Linux Interview Questions in 2024

Q1. What command is used to display the current date and time in Linux?
Ans: The date command displays the current date and time in the specified format. By default, it uses the system’s locale settings. You can customize the format using options like +%H:%M:%S for hours, minutes, and seconds, +%d/%m/%y for day, month, and year, etc.

Example:

date +%H:%M:%S %d/%m/%Y

Q2. How do you list files and directories in a directory in Linux?
Ans: The ls command lists the contents of a directory. You can use options like:

  • -a: Show hidden files.
  • -l: Display detailed information in long format.
  • -R: Recursively list files in subdirectories.
  • -h: Human-readable file sizes (e.g., KB, MB, GB).

Example:

ls -lhR

Q3. What command is used to create a new directory in Linux?
Ans: The mkdir command creates a new directory. You can create multiple directories at once by providing space-separated names.

Example:

mkdir documents data backups

Q4. How do you remove a directory in Linux?
Ans: The rmdir command removes an empty directory. To remove a directory with its contents, use rm -rf, but exercise extreme caution as this is irreversible.

Example:

rmdir empty_dir
rm -rf full_dir_with_contents  # Use with caution!

Q5. Explain the difference between rm and rm -r?
Ans:

  • rm removes files or directories, but only empty directories.
  • rm -r recursively removes a directory and all its contents, including subdirectories and files. Use it carefully due to its permanent nature.

Q6. How do you copy files and directories in Linux?
Ans: The cp command copies files and directories. You can specify the source and destination paths.

Example:

cp report.txt /home/user/documents
cp -r project_folder /media/backup_drive

Q7. How do you move files and directories in Linux?
Ans: The mv command moves or renames files and directories. Use the same syntax as cp, but the source file is removed after the move.

Example:

mv report.txt /home/user/reports
mv project_folder /media/new_location

Q8. What is the command to rename a file or directory in Linux?
Ans: As mentioned above, the mv command can be used to rename a file or directory by specifying the new name as the destination path.

Q9. How do you create an empty file in Linux?
Ans: The touch command creates an empty file if it doesn’t exist, or updates the modification time of an existing file.

Example:

touch new_file.txt

Q10. How do you display the contents of a file in Linux?
Ans: Several commands can display file contents:

  • cat: Suitable for small files, displays entire content at once.
  • less: Useful for large files, allows scrolling page by page.
  • more: Similar to less, but advances a full screen at a time.

Example:

cat small_file.txt
less large_file.txt
more very_large_file.txt

Q11. Explain the difference between cat, less, and more commands.
Ans:

  • cat: Shows the entire file at once, good for small files.
  • less: Displays one screen at a time, allows scrolling, useful for large files.
  • more: Similar to less, but advances a full screen at a time.

Q12. How do you search for a specific text pattern in a file in Linux?
Ans: The grep command searches for lines containing a specified pattern.

Example:

grep "error" error_log.txt

Q13. What is the command to find files in Linux?
Ans: The find command is a versatile tool for searching for files and directories in Linux. It offers various options to filter your search based on:

  • Path: Specify the starting directory where the search begins (e.g., / for the entire system, . for the current directory).
  • Name: Use -name or -iname to match filenames (case-sensitive or case-insensitive).
  • Type: Filter by file types (e.g., -type f for regular files, -type d for directories).
  • Permissions: Check permissions using -perm or -permmode.
  • Size: Search based on file size with -size or -sizek (kilobytes).
  • Date & Time: Look for files modified or accessed within specific dates or times using -mtime-atime, or -ctime.
  • Owner/Group: Find files owned by a specific user or group with -user or -group.

Example:

# Find all files named "report.txt" in the current directory and subdirectories:
find . -name "report.txt"

# Find all empty files in the "/home" directory:
find /home -empty

# Find all regular files with size greater than 10 MB:
find / -type f -size +10M

# Find all files owned by user "john" in the "/tmp" directory, modified in the last 24 hours:
find /tmp -type f -user john -mtime -1

Q14. How do you change permissions of a file or directory in Linux?
Ans: The chmod command allows you to modify file or directory permissions. Permissions are represented by a three-digit octal number, where each digit indicates read (r), write (w), and execute (x) permissions for owner, group, and others, respectively.

Example:

# Change permissions of "myfile.txt" to allow read and write for owner and group, read-only for others (755):
chmod 755 myfile.txt

# Make "mydirectory" executable for everyone (111):
chmod 111 mydirectory

Q15. Explain the meaning of file permissions in Linux?
Ans:
Linux file permissions control access to files and directories. Each file has three permission levels:

  • Owner: User who owns the file.
  • Group: Group the owner belongs to.
  • Others: Everyone else on the system.

Each level has three permissions:

  • Read (r): Allows reading the file’s contents.
  • Write (w): Allows modifying or deleting the file.
  • Execute (x): Allows executing the file (if it’s an executable).

The permission mask is a three-digit octal number, where each digit represents the permissions for a level (owner, group, others). Each digit is calculated by adding the values of the relevant permissions:

  • 4: Read
  • 2: Write
  • 1: Execute

For example, 755 represents:

  • Owner: Read, Write, Execute (4 + 2 + 1)
  • Group: Read, Execute (4 + 1)
  • Others: Read, Execute (4 + 1)

Q16. How do you change ownership of a file or directory in Linux?
Ans: Use the chown command to change the owner of a file or directory. You can specify the new owner name or user ID and optionally the new group name or group ID.

Example:

# Change owner of "myfile.txt" to user "jane":
chown jane myfile.txt

# Change owner and group of "mydirectory" to "john" and "developers" respectively:
chown john:developers mydirectory

Q17. What is the command to display disk usage in Linux?
Ans: The df command shows disk usage information for mounted file systems.

Example:

df -h

Q18. How do you check the current working directory in Linux?
Ans:There are two main ways to check the current working directory in Linux:
1. Using pwd command:

The pwd command (short for “print working directory”) displays the absolute path of the directory you are currently in. It’s a quick and simple way to see your location within the file system hierarchy.

Example:

pwd

This will return the absolute path of your current working directory. For instance, it might print something like “/home/user/Desktop”.

2. Using ls -l command:

While not specifically designed for displaying the current directory, the ls -l command (list with details) shows detailed information about files and directories in the current location. This includes the full path of the current directory itself.

Example:

ls -l

The first line of the output usually starts with something like “total X”, where X is the number of entries in the directory. Then, it will list information about each file and directory, including the permissions, owner, group, size, and name. The last entry, usually highlighted or emphasized, shows the name of the current directory itself, giving you the absolute path.

Both methods offer different approaches:

  • pwd is quick and concise, directly providing the absolute path.
  • ls -l offers more information about the current directory and its contents, including the path as part of the details.

Q19. What command is used to print the last few lines of a file in Linux?
Ans: The tail command is used to print the last lines of a file. By default, it shows the last 10 lines. You can specify the number of lines to print using the -n option.

# Print the last 5 lines of "myfile.txt":
tail -n 5 myfile.txt

# Print all lines from the end of the file:
tail -f myfile.txt

Q20. How do you print the first few lines of a file in Linux?
Ans: The head command is used to print the first lines of a file. By default, it shows the first 10 lines. You can specify the number of lines to print using the -n option.

# Print the first 2 lines of "myfile.txt":
head -n 2 myfile.txt

Q21. Explain the use of grep command in Linux?
Ans: The grep command searches for lines matching a specific pattern in a file. It’s very useful for filtering text and finding specific information.

# Find lines containing "error" in "error_log.txt":
grep "error" error_log.txt

# Find lines starting with "warning" in "system_log.txt", case-insensitive:
grep -i "^warning" system_log.txt

# Find lines containing "root" and "login" in "access_log.txt":
grep -w "root login" access_log.txt

Q22. How do you count the number of lines, words, and characters in a file in Linux?
Ans: You can use several commands for this:

  • wc: Counts lines, words, and bytes in a file.
  • cat | wc: Pipes the file content to wc for counting.
# Count lines, words, and characters in "myfile.txt":
wc myfile.txt

# Count words and characters in "large_file.txt":
cat large_file.txt | wc -w -c

Q23. What command is used to compress files in Linux?
Ans: Several compression tools are available, including:

  • gzip: Compresses single files to .gz extension.
  • bzip2: Compresses single files to .bz2 extension.
  • tar: Creates archives that can contain multiple files and directories.
# Compress "myfile.txt" with gzip:
gzip myfile.txt

# Compress "directory" with bzip2:
tar -jcf directory.tar.bz2 directory

# Create a compressed archive of multiple files:
tar -zcf files.tar.gz file1.txt file2.txt

Q24. How do you extract files from a compressed archive in Linux?
Ans: Use the same tools as for compressing with the extraction option:

# Extract "myfile.txt.gz":
gunzip myfile.txt.gz

# Extract all files from "directory.tar.bz2":
tar -xf directory.tar.bz2

# Extract specific files from "files.tar.gz":
tar -xzf files.tar.gz file1.txt file2.txt

Q25. Explain the use of tar command in Linux?
Ans: The tar command is a versatile tool for archiving and manipulating files. It can create, extract, list, and add/remove files from archives.

  • tar -c: Create an archive.
  • tar -x: Extract files from an archive.
  • tar -t: List contents of an archive.
  • tar -r: Add files to an existing archive.
  • tar -z-j: Use compression (gzip, bzip2) during archiving/extraction.

Q26. What is the command to list running processes in Linux?
Ans: The ps command lists currently running processes. You can use various options to filter and format the output.

# List all running processes:
ps aux

# List processes owned by a specific user:
ps aux | grep username

# List processes using more than 10% CPU:
ps aux | grep -E "%CPU +> 10"

Q27. How do you terminate a process in Linux?
Ans: To terminate a process in Linux, you can use the kill command with the process ID (PID). Here are some ways to do it:

1. Using PID:

  • Find the PID of the process you want to terminate using commands like ps aux or top.
  • Use the kill command with the PID followed by the signal to send:
kill PID SIGNAL

Common signals:

  • SIGTERM (default): Gracefully terminates the process, allowing it to clean up before exiting.
  • SIGINT (Ctrl+C): Sends the same signal as pressing Ctrl+C to the terminal, often used for immediate termination.
  • SIGKILL (9): Terminates the process immediately without warning or cleanup. Use with caution as it can lead to data loss.

Example:

# Terminate process with PID 1234 using SIGTERM:
kill 1234 SIGTERM

# Terminate process with PID 1234 using SIGKILL (use with caution):
kill -9 1234

2. Using process name:

  • You can use pkill to terminate processes by name (exact match)
pkill process_name

Example:

# Terminate all processes named "firefox":
pkill firefox

3. Sending signals to specific user processes:
Use killall to terminate all processes owned by a specific user:

killall username

Example:

# Terminate all processes owned by user "john":
killall john

Important notes:

  • Make sure you identify the correct process before terminating it. Terminating the wrong process can have unintended consequences.
  • Use SIGKILL with caution, as it can lead to data loss or system instability.
  • Always consider the impact of terminating a process before doing so.

Q28. Explain the use of ps command in Linux?
Ans: The ps command, short for “process status,” is a fundamental utility in Linux used to list and display information about currently running processes on the system. It provides valuable insights into various aspects of your system’s operation, such as:

  • Active processes: You can see which programs and tasks are currently running, along with their resource usage.
  • Process details: This includes information like process ID (PID), user ownership, CPU and memory usage, start time, and command line arguments.
  • System state: By monitoring process activity, you can gain insights into overall system load, identify potential bottlenecks, and troubleshoot issues.

Common options for using ps:

The ps command offers various options to customize its output and filter processes based on specific criteria. Here are some common options:

  • -a: Show all processes, including those in the background.
  • -u: Filter by user.
  • -x: Show a more detailed format.
  • -e: Select processes by exact match of command name.
  • -f: Display full information in long format.
  • -l: Display even more detailed information in long format.

Examples of using ps:

  • List all running processes:
ps aux

Show processes owned by a specific user:

ps aux | grep username

List processes using more than 10% CPU:

ps aux | grep -E "%CPU +> 10"

Display detailed information about a specific process:

ps -fp PID

Understanding ps output:

The output of the ps command can vary depending on the options used. However, it generally includes columns with information like:

  • PID: Process ID, a unique identifier for each process.
  • TTY: Terminal associated with the process (often blank for background processes).
  • STAT: Process state (e.g., running, sleeping, waiting).
  • TIME: CPU time used by the process in minutes and seconds.
  • %CPU: Percentage of CPU used by the process.
  • %MEM: Percentage of memory used by the process.
  • VSZ: Virtual memory size of the process in kilobytes.
  • RSS: Resident set size, the amount of memory currently used by the process in kilobytes.
  • COMMAND: Name of the command that started the process.

Additional notes:

  • The ps command is a powerful tool, but it can be overwhelming for beginners. Start with basic options and gradually explore more advanced ones as you gain familiarity.
  • Remember that the specific output and available options might vary slightly depending on your Linux distribution and version.

Q29. What command is used to find out information about the system hardware in Linux?
Ans: Several commands provide system hardware information:

  • lshw: Lists hardware components and details.
  • free: Shows memory usage.
  • df: Displays disk usage.
  • top: Monitors CPU, memory, and process usage.
  • uname -a: Gets kernel version and system information.

Q30. How do you check the available disk space in Linux?
Ans: There are two main ways to check the available disk space in Linux:

1. Using the df command:

The df command (stands for “disk free”) is the most commonly used tool for checking disk space. It provides information about mounted file systems, including:

  • Filesystem: Name of the mounted file system (e.g., //home).
  • Size: Total disk space of the file system.
  • Used: Space currently used by files and directories.
  • Available: Remaining free space for storing data.
  • Use%: Percentage of used space.
  • Mounted on: Directory where the file system is mounted.

To use the df command, simply run it in your terminal:

df

This will display information about all mounted file systems on your system. You can use various options to customize the output, such as:

  • -h: Show human-readable sizes (e.g., GB, MB) instead of byte counts.
  • -T: Display the filesystem type (e.g., ext4, XFS).
  • -l: Show more detailed information, including inodes used.

2. Using the du command:

The du command (stands for “disk usage”) allows you to check the disk usage of individual files or directories. It calculates and displays the total size of files and subdirectories within a specified path.

To use du to check available space, you can do:

du -sh /

This will display the total size and available space for the root directory (/). You can replace / with any other directory path you want to check.

Here are some common options for du:

  • -h: Show human-readable sizes.
  • -s: Only show the total size of a directory, not individual files.
  • -d: Specify the depth to which subdirectories should be examined.

Choosing the right option:

  • Use df for a quick overview of available space on all mounted file systems.
  • Use du to check the size and available space of specific directories or files.

Q31. Explain the use of df command in Linux?
Ans: df displays information about mounted file systems, including:

  • File system name (e.g., //home).
  • Size (total disk space).
  • Used space.
  • Available space.
  • Percentage of used space.
  • Mounted on (directory where the file system is mounted).

Q32. What command is used to find out the IP address of a Linux system?
Ans: Several commands can be used:

  • ip addr: Lists network interfaces and IP addresses.
  • hostname -I: Displays the system’s IP address(es).
  • ifconfig: Older network configuration tool, may still be available.

Q33. How do you check the network connectivity in Linux?
Ans: You can use ping to test connectivity to a specific host:

ping google.com

netstat and ip commands provide more detailed network information.

Q34. What is the command to restart the network service in Linux?
Ans: The specific command depends on your system and service manager. Common options include:

  • systemctl restart networking.service (systemd)
  • /etc/init.d/networking restart (SysV init)

Q35. How do you find out the version of Linux distribution you are using?
Ans: Use cat /etc/*-release or lsb_release -a.

Q36. What is the command to shut down the system in Linux?
Ans: Use shutdown with the following options:

  • -h: Halt (power off) after stopping processes.
  • -r: Reboot after stopping processes.
# Shut down in 5 minutes:
shutdown -h +5

# Reboot in 10 minutes:
shutdown -r +10

Q37. How do you schedule tasks to run at a specific time in Linux?
Ans: Use the crontab command to create and edit cron jobs.

crontab -e

This opens the crontab editor where you can define tasks to run at specific times or intervals.

Q38. What command is used to view the history of commands executed in the terminal?
Ans: The history command shows a list of previously executed commands.

Q39. How do you create a symbolic link in Linux?
Ans: Use the ln -s command to create a symbolic link (shortcut) to a file or directory.

# Create a symbolic link to "myfile.txt" named "shortcut.txt":
ln -s myfile.txt shortcut.txt

Q40. What is the command to find out information about a command in Linux?
Ans: In Linux, you can use the man command to find out information about another command. “man” stands for manual, and it provides detailed documentation on various commands and utilities available in the Linux system.

For example, to find out information about the ls command, you would type:

man ls

This command will display the manual page for the ls command, which includes its description, usage, options, and examples.

Q41. How do you install software packages in Linux?
Ans:In Linux, you can install software packages using package managers like apt, yum, dnf, or zypper, depending on the distribution you’re using. These package managers fetch software packages from online repositories and handle dependencies automatically during installation.

Q42. Explain the use of apt-get command in Linux?
Ans:apt-get is a command-line tool used in Debian-based distributions such as Ubuntu. It is used to handle package management tasks like installation, removal, and upgrading of software packages. For example, to install a package using apt-get, you would use the command sudo apt-get install <package_name>.

Q43. What is the command to update the package list in Linux?
Ans:The command to update the package list in Linux varies depending on the package manager being used. For apt, you would use sudo apt update. This command refreshes the local package index to reflect the latest changes in the repositories.

Q44. How do you upgrade all installed packages in Linux?
Ans: To upgrade all installed packages in Linux, you can use the command sudo apt upgrade for Debian-based distributions like Ubuntu. This command upgrades all installed packages to their latest available versions.

Q45. What command is used to uninstall software packages in Linux?
Ans:
To uninstall software packages in Linux, you can use the apt-get remove command in Debian-based distributions. For example, sudo apt-get remove <package_name> will remove the specified package from your system.

Q46. Explain the use of rpm command in Linux?
Ans: The rpm command is used in RPM-based Linux distributions like Red Hat Enterprise Linux (RHEL) and CentOS to manage software packages. It allows you to install, query, verify, update, and remove individual software packages in the RPM format.

Q47. How do you check the status of a service in Linux?
Ans:
To check the status of a service in Linux, you can use the systemctl status command followed by the name of the service. For example, systemctl status sshd will display the status of the SSH service.

Q48. What is the command to start a service in Linux?
Ans:
To start a service in Linux, you can use the systemctl start command followed by the name of the service. For example, sudo systemctl start sshd will start the SSH service.

Q49. How do you stop a service in Linux?
Ans:
To stop a service in Linux, you can use the systemctl stop command followed by the name of the service. For example, sudo systemctl stop sshd will stop the SSH service.

Q50.How do you navigate between directories in Linux?
Ans: To navigate between directories in Linux, you primarily use the cd (change directory) command. Here’s how it works:

  1. Changing to a Specific Directory:
    • To change to a specific directory, you use the cd command followed by the directory path. For example:
cd /path/to/directory

Moving Up to the Parent Directory:

  • To move up to the parent directory of your current location, you use cd with ... For example:
cd ..

Moving to the Home Directory:

  • To move to your home directory (usually /home/username), you can use cd without any arguments. For example:
cd

Using Relative Paths:

  • You can use relative paths to move between directories. For instance, if you’re in /home/user, and you want to move to a directory named Documents within it, you can use:
cd Documents
  1. Using Tab Completion:
    • You can use tab completion to quickly navigate directories. For instance, if you type cd /ho and press Tab, it will autocomplete to /home.
  2. Using Environment Variables:
    • You can also use environment variables for navigation. For instance, if you have an environment variable named $MY_DIR set to /path/to/directory, you can use:
cd $MY_DIR

Remember, Linux file systems are hierarchical, so understanding directory structures and how to navigate efficiently is crucial.

Click here for more Linux commands related interview questions and answer.

To know more about Linux commands please visit Linux official site.

About the Author