Location>code7788 >text

Linux final exam questions (1)

Popularity:808 ℃/2025-05-06 14:43:28

Linux final exam questions

1. Multiple choice questions (20 points in total, 2 points in each question)

1. Which of the following environment variables represents shell search external command or program path (C

answer:

ENV is used to display the current environment variable, PWD is used to display the current working directory, and ROOT is used to represent the super user

2. In order to achieve the permissions of the owner and the same group of users to read (r), write (w) and execute (x), while other users can only access read-only. When setting the permission value of the file, it should be set to (D)

A、 747 B、744 C、775 D、774

answer:

1️⃣r (read): 4 w (write): 2 x (execution): 1

Therefore, the calculation is as follows:

Owner: Read (4) + Write (2) + Execute (1) = 7

Users in the same group (Group): Read (4) + Write (2) + Execute (1) = 7

Others: Read (4)

Therefore, permissions should be set to 774

3. To end the process using the process name, use (D)Order.

A、ps -d B、psfree C、profree D、kill

answer:

psThe command is used to display the status of the current process.-dOptions are usually used to specify which processes are displayed (such as only the processes of the current terminal) but are not used to terminate processes by themselves.

psfree:? ? ? ? ? This command was not found

profree:? ? ? ? ? ? This command was not found

4. By default, the administrator creates a user and will be (BCreate a user home directory under the ) directory.

A./usr B./home C./root D./etc

answer:

/usrDirectories are usually used to store system software and program resources, such as executable files, library files, and documents.

/homeIt is the standard storage location of the user's home directory in Linux system. By default, when the administrator creates a new user, the system will/homeCreate a subdirectory named after the user as its home directory under the directory.

/rootIt is the exclusive home directory of the system administrator (root user).

/etcDirectories are used to store system configuration files, such as user account information, network configuration, service configuration, etc.

The first process started by init The first script program started by (D

A、/etc/fstab B、/etc// C、/etc/inittab D、/etc//

answer:

initIt is the first process after the Linux system is started (PID is 1), responsible for initializing the system environment and starting other processes.

initProcess startup process

After the kernel starts, it will startinitprocess.

initThe process will first execute the global system initialization script, usually/etc//(In some systems it may be/etc/). This script is responsible for basic tasks such as mounting the file system, setting the host name, initializing the network, and loading kernel modules.

/etc/fstabIt is a configuration file, not a script program, used to define a file system that is automatically mounted when the system starts.

/etc//is a directory that stores start and stop scripts for all services. It is not a script program itself, but a directory containing multiple scripts..dThe ending represents a directory, usually containing a set of scripts or configuration files

/etc/inittabis a configuration file that definesinitThe behavior of the process (such as the default run level, startup script, etc.). It's not a scripting program,initconfiguration file.

6. The following (B) directive can be used to display the routing table of the current host.

A、netstat -rn B、route C、print route D、show ip route

answer:

The routing table is used to define the forwarding path of packets from the local host to other networks.

netstatIt is a network statistics tool used to display network connections, routing tables, interface statistics and other information.-rThe option indicates that the routing table is displayed.-nOptions indicate the display of address and port in numeric form (the host name and service name are not resolved).

routeis a command used to display and operate IP routing tables. Direct inputroute(without any options) will display the routing table for the current host.

print routeNot a standard command in Linux. In Windows,route printThe routing table can be displayed, but it does not work in Linux.

show ip routeIt is a command in network devices such as Cisco IOS, which is used to display IP routing tables. Not valid in Linux.

The content stored in the system directory /boot is (A

A. Store the system's kernel files and bootloader files

B. Store all important library files

C. Application storage directory

D. Store most configuration files and subdirectories of the system

answer:

/bootDirectory is mainly used to store files related to system startup. These files include kernel image, initial RAM disk (initramfs or initrd), and bootloader (such as GRUB) configuration files and modules.

Important library files are usually stored in/libor/usr/libin the directory.

Applications are usually stored in/usr/bin/usr/local/binor/optetc.

Most of the system's configuration files are stored in/etcin the directory.

Supported file systems are (ABCD)

A、Swap B、NFS C、ISO9660 D、proc

answer:

❓The answer is BC

Swap (switch space) is a mechanism used in Linux for virtual memory. Although Swap is not a file system in the traditional sense (such as ext4, XFS, etc.), Linux does support Swap partitions or Swap files and treats it as a special "file system" type.

NFS (Network File System) is a network file system protocol that allows files to be shared across the network between different hosts. The Linux kernel supports NFS client and server side, so NFS is a file system type supported by Linux. By mounting the NFS shared directory, you can access the remote file system locally.

ISO9660 is a file system standard for optical discs (such as CD-ROM, DVD). Linux supports mounting disc images in ISO9660 format (such as.isofile), so ISO9660 is a file system type supported by Linux.

/procIt is a virtual file system (pseudo-filesystem) in Linux, used to provide kernel and process information interface. It is not a traditional file system stored on disk, but is generated dynamically by the kernel. although/procIt is not a type that stores file system (such as ext4, XFS, etc.), but it is a special file system type, and the Linux kernel explicitly supports it. In Linux,/procThe file system is always mounted on/procIn the directory, it is used to access system information.

9. Which of the following commands can be used to display file contents (ABCD)

A、cat B、more C、tail D、head

answer:

cat is used to display file content, more is used to display file content by paging, tail is used to display file content at the end of the file, and head is used to display file content at the beginning of the file

10. Which of the following contents are included in the /etc/password file (ABCD)

A. User ID B. User password C. User name D. She11 used by the user

answer:

cat /etc/passwd output:

[root@node2 etc]# cat passwd
root❌0:0:root:/root:/bin/bash
bin❌1:1:bin:/bin:/sbin/nologin
daemon❌2:2:daemon:/sbin:/sbin/nologin

/etc/passwdThe password is stored in the placeholder (usuallyx), not the actual encrypted password.

2. Short answer questions (50 points in total, 10 points in each question)

What are the main functions of the system's shell as the operating system shell?

answer:As the shell of the operating system, the main function of the Linux system is to provide an interface for users to interact with the kernel, be responsible for interpreting and executing commands entered by users, support interactive command line operations, script programming to achieve automated tasks, and provide input/output redirection and pipeline functions to flexibly process data flow, thereby efficiently managing system resources and performing complex operations.

2. In Shell's variable application, what is the difference between the three quotation marks?

answer:In double quotes, all characters except $, ", and \ are interpreted as the character itself.

All characters in single quotes, including the special characters $, ", and \ will be interpreted as the characters themselves and become ordinary characters;

The string in the backtick marks will be interpreted as a shell command to execute.

3. When executing the command ls -l, the results are displayed as follows:

-rw-r--r-- 1 john 2017 jul 16 11:58 data

(1) What permissions does user john have to the file?

answer:userjohnHave read to the file (r) and write (w) permissions (-rw-), but not executed (x) permissions.

(2) Neither the user tom nor root are members of the john group. What kind of access rights do they have to the file?

answer:usertomOnly read to this file (r) permissions (r--)。

userrootAs a super user, you have full access to all files by default (read, write, and execute) and is not restricted by file permissions.

(3) How to enable any user to read, write and execute the file?

answer:usechmodCommand sets file permissions to777, enter the command:chmod 777 data

(4) How to change the file owner to user tom?

chown tom data

If you need to change the group at the same time, you can add:group,For examplechown tom:users data

4. A system administrator needs to complete the following repetitive work every day, please prepare a task scheduling plan.

👆Test points:

cronIn the task scheduling system, the basic format of time definition

* * * * * <command-to-execute>
 | | | | | |
 | | | | +----- Day of the week (0 - 7) (both 0 and 7 represent Sunday)
 | | | +------- Month (1 - 12)
 | | +------------ Date (1 - 31)
 | +-----------------------------------------------------------------------------------------------------------------------------
 +--------------- Minutes (0 - 59)

 #Use of special characters
 Asterisk (*)
 Indicates "each" or "any".
 For example: * in the minute field means "per minute", and in the hour field means "per hour".

 comma(,)
 Used to specify multiple discontinuous time points.
 For example: 0 9,17 * * * means execution at 9:00 and 17:00 every day.

 Horizontal line (-)
 Used to specify a time range.
 For example: 0 9-17 * * * means every hour between 9:00 and 17:00 every day (9:00, 10:00, ..., 17:00).

 Slash (/)
 Used to specify the time interval (step length).
 For example: */2 * * * means execution every 2 minutes, 0 */2 * * means execution every 2 hours.

 #Date and Day of the Week conflict handling: In standard Linux cron, the date and day of the week fields are "or" relationships.  If both date and day of the week are specified, the task will be executed when either condition is met.

Redirect operator

> Used to redirect the output of the command to a file.
 >> Append the output of the command to the end of the file instead of overwriting the file content.
 2> Redirect the command's error output to the file.
 &> Redirect the standard output and error output of the command to the file simultaneously.

Command Line Tools

ls
 Function: List the contents of the directory.
 Common options:
 -l: Detailed list (permissions, owners, sizes, modification time, etc.).
 -a: Show all files (including hidden files).
 -h: Readable file size (such as KB, MB).

 cd
 Function: Switch the current working directory.

 pwd
 Function: Displays the full path to the current working directory.

 mkdir
 Function: Create a new directory.
 Common options:
 -p: Recursively create the parent directory (if needed).

 rm
 Function: Delete files or directories.
 Common options:
 -r: Recursively delete the directory and its contents.
 -f: Forced deletion (no prompt for confirmation).

 cp
 Function: Copy files or directories.
 Common options:
 -r: Recursively copy the directory.

 mv
 Function: Move or rename files or directories.

 locate
 Features: Quickly find files (based on pre-built database).
 Note: You need to run updatedb first to update the database.

 cat
 Function: View file content or connect multiple files.

 less and more
 Function: View file contents by paging (less is more powerful than more, supports front and back page turn).

 head and tail
 Function: View the beginning or ending part of the file.
 Common options:
 -n: Specify the number of rows.

 grep
 Function: Search for text mode in file or output.
 Common options:
 -i: Ignore case.
 -r: Recursively search the directory.

 sed
 Function: Stream editor for text replacement, deletion, insertion, etc.
 Example:
 sed 's/old/new/g' # Replace "old" with "new"

 awk
 Function: Powerful text processing tool, often used to extract and format data.
 Example:
 bash
 awk '{print $1, $3}' # Print columns 1 and 3 of each row

 vim and nano
 Function: Text editor.
 vim: Powerful but steep learning curve.
 nano: Simple and easy to use, suitable for beginners.

 ps
 Function: View the currently running process.
 Common options:
 aux: Show all processes for all users.

 top and htop
 Function: Real-time monitoring of system processes and resource usage.
 htop: It is an enhanced version of top, with a more friendly interface.

 kill and pkill
 Function: Terminate the process.
 kill: Terminate the process through the process ID (PID).
 pkill: Terminate the process by the process name.

 bg and fg
 Function: Control background and foreground processes.
 bg: Put the suspended job in the background to run.
 fg: Bring backend jobs to the foreground.

 jobs
 Function: List jobs in the current shell session.

 uname
 Function: Display system information (such as kernel name, version, etc.).
 Common options:
 -a: Show all information.

 df
 Function: Display disk space usage.
 Common options:
 -h: Human-readable format.

 du
 Function: Displays the disk usage of directories or files.
 Common options:
 -h: Human-readable format.
 -s: Show totals only.
 Example:
 du -sh /var/log # Show the total size of the /var/log directory

 free
 Function: Display memory and swap space usage.
 Common options:
 -h: Human-readable format.

 uptime
 Function: Displays system running time and current load.

 ifconfig and ip
 Function: View and configure the network interface.
 ifconfig: Older tool (some systems have been deprecated).
 ip: modern alternative tool.

 ping
 Function: Test network connectivity.

 netstat and ss
 Function: View network connection, routing table and other information.
 netstat: Older tool.
 ss: a modern alternative tool.

 nslookup and dig
 Function: Query DNS information.
 dig: More powerful.
 Example:
 dig # query DNS records

 wget and curl
 Function: Download files from the network.
 wget: Suitable for downloading files.
 curl: suitable for sending HTTP requests and debugging APIs.
 Example:
 wget / # Download file
 curl -I # View HTTP header information

 sudo
 Function: Execute commands as other users (usually root).
 Example:
 bash
 sudo apt update # Update package list with root permissions

 su
 Function: Switch user identity.
 Example:
 bash
 su - username # Switch to other users

 passwd
 Function: Change user password.
 Example:
 passwd # Modify the current user's password

 chmod
 Function: Change the permissions of files or directories.
 Common options:
 755: The owner can read, write, and execute, and other users can read and execute.

 chown
 Function: Modify the owner of a file or directory.
 Example:
 chown user:group # Modified owner and group

 tar
 Features: Packaging and unpacking files (usually used in conjunction with compression tools).
 Common options:
 -c: Create an archive file.
 -x: Unzip the archive file.
 -z: Use gzip to compress/decompress.
 -j: Use bzip2 to compress/decompress.
 -v: Show detailed output.
 Example:
 tar -czvf /path/to/dir # Create gzip compressed tar package
 tar -xzvf # Unzip gzip compressed tar package

 gzip and gunzip
 Function: Compress and decompress files (.gz format).
 Example:
 gzip # compressed files
 gunzip # Unzip the file

 zip and unzip
 Function: Compress and decompress files (.zip format).
 Example:
 zip # Create zip file
 unzip # unzip zip file

 ssh
 Features: Remotely log in to other Linux/Unix servers.
 Example:
 ssh username@hostname # Remote login

 scp
 Features: Securely copy files between local and remote systems.
 Example:
 scp username@hostname:/remote/path/ # Upload file
 scp username@hostname:/remote/path/ . # Download the file

 rsync
 Function: Efficiently synchronize files and directories (support incremental synchronization).
 Example:
 rsync -avz /local/path/ username@hostname:/remote/path/ # Synchronize directory

 crontab
 Function: Manage timing tasks (cron jobs).
 Example:
 bash
 crontab -e # Edit the cron job of the current user

 history
 Function: View command line history.

(1) Save the number of online users to the num file at 9 am and 5 pm every day;

0 9,17 * * * who >> /opt/test/num 

Notice:Here >> is to append content to the end of the file. You can also use >, but it will overwrite the content of the original file.

(2) Backup pub file data into the data file every 2 hours from Monday to Friday;

0 */2 * * 1-5 cp /opt/test/pub /opt/test/data  

hint:*/2 means every two hours.

cp: Copy command.

cp -r source file path target file path

  • -ror-R: Recursively copying the directory and its contents (when copying a directory).
  • -i: Interactive copy, prompt the user to confirm before overwriting.
  • -v: Displays detailed output and displays the copied file name.
  • -u: Copy only if the source file is newer than the target file, or if the target file does not exist.

(3) Delete temporary files (all files in the /temp directory) every Friday at 6:00 pm;

0 18 * * 5 rm -rf /temp/*  

Notice:rm -rf is to recursively force delete files and directories.

/temp/* means to delete all files and subdirectories under the temp directory.

(4) Send a message to all users at 8:30 on the 1st of each month, reminding you to submit a work summary last month.

30 8 1 * * wall "Please prepare to submit a summary of last month's work!"

Notice:wallis a command line tool that sends messages to all users logged into the system.wallIt is the abbreviation of "write all"

5. Read the functions of the following programs and the execution results after reading command line parameters.

#!/bin/bash

 echo 'key in a number (1-10):' #Show prompt information, requiring the user to enter a number (1-10)
 read a #Storage the value entered by the user into the variable a

 if [ "$a" -lt 1 -o "$a" -gt 10 ] #Check whether the entered number is less than 1 or greater than 10
 Then
   echo 'Error Number.' #If the condition is met, output Error Number. and exit the script (exit)
   exit
 elif [ ! "$a" -lt 5 ] #Check whether the entered number is not less than 5 (that is, greater than or equal to 5)
 Then
   echo "It's not less 5." #If the condition is met, output It's not less 5.
 else
   echo "It's less 5." #If the input number is between 1-4, output It's less 5.
 fi

Run #bash 6

👆Test points:

Relational operators

Operators illustrate Example
-eq equal if [ $a -eq $b ]
-ne Not equal to if [ $a -ne $b ]
-gt Greater than if [ $a -gt $b ]
-lt Less than if [ $a -lt $b ]
-ge Greater than or equal to if [ $a -ge $b ]
-le Less than or equal to if [ $a -le $b ]

untie:This program is used to read the numbers entered by the user (1-10) and output different prompt information according to the input numbers.

echo is a basic command line tool for outputting the values ​​of text or variables to standard output.

Here -o means or is an old-style writing method, -a means and.

enter6Output result:It's not less 5

3. Comprehensive programming questions (30 points in total, 15 points in each question)

1. Write a shell script. The first position parameter is the specified directory. The specified position parameter is the file in the specified directory of the first position parameter, displaying the contents of these files.

untie:Batch view of the file contents in the specified directory.

#!/bin/bash

 # Check whether directory parameters are provided
 #Check the number of command line parameters. If no parameters are provided ($# -lt 1), the usage prompt is displayed and exited
 #$0 represents the script's own name, <directory> is a required parameter, and can be followed by multiple optional file names.

 if [ $# -lt 1 ]; then
   echo "Usage: $0 <directory> [file1] [file2] ..."
   exit 1
 fi

 # Get directory path
 #Extract the first parameter as the target directory path

 directory="$1"

 # Check whether the directory exists
 #Use -d to test the operator to verify whether the directory exists
 #Perform double quote wrapping of the path to correctly handle directory names containing spaces

 if [ ! -d "$directory" ]; then
   echo "Error: Directory '$directory' does not exist."
   exit 1
 fi

 # traverse subsequent parameters (file)
 The #shift command moves the parameter list one left by one, so that $1 becomes the first file name
 #Travel the remaining parameters ("$@" retain file names with spaces)
 #Use -f test operator to check: whether the file exists or not? Whether it is a normal file (excluding special types such as directories/device files)
 #For valid files: Print divider (including file name) Use cat to display file content Print end divider
 #For invalid files: output warning information (including specific path)

 shift # Remove the first parameter (directory), the remaining parameters are files
 for file in "$@"; do
   # Check if the file exists and is a normal file
   if [ -f "$directory/$file" ]; then
     echo "===== Contents of $file ====="
     cat "$directory/$file"
     echo "========================================================
   else
     echo "Warning: '$directory/$file' is not a valid file or does not exist."
   fi
 done

2. Write a program to implement multi-process programming. The main process obtains the current system time and writes it to a file every 2 seconds. The child process opens the file and the content of the read file is displayed on the screen.

untie:Below is the time_logger.sh script.

#!/bin/bash

 # Define file path
 output_file="time_log.txt"

 # Clear or create a file
 > "$output_file"

 # Main process: Write the current time to the file every 2 seconds
 #( ... ) &: Start a background subshell process, and the code in brackets will run in the subshell.
 #while true; do ... done: Infinite loop, continuously execute the code in brackets.
 #current_time=$(date "+%Y-%m-%d %H:%M:%S"): Call the date command to obtain the current time, the format is year-month-day hour: minute: seconds, and assign the result to the variable current_time.

 (
   while true; do
     current_time=$(date "+%Y-%m-%d %H:%M:%S")
     #Append the current time to the time_log.txt file.
     echo "Main process writes: $current_time" >> "$output_file"
	 #Pause for 2 seconds and continue the loop.
     sleep 2
   done
 ) &

 # Get the PID of the main process (for subsequent management)
 #$!: Get the PID of the previous background process (i.e. the PID of the main process).
 #main_pid=$!: Assign the PID of the main process to the variable main_pid for subsequent management (such as terminating the process).

 main_pid=$!

 # Subprocess: Read the file content and display it to the screen
 (
   while true; do
     if [ -f "$output_file" ]; then
       echo "Child process reads:"
       cat "$output_file"
       echo "----------------------------------------------------------------------------------------------------------------------------
     fi
     sleep 1 # The read frequency of the child process can be higher than the write frequency of the main process
   done
 ) &

 # Get the PID of the child process (for subsequent management)
 #Get the PID of the previous background process (i.e. the PID of the child process).
 #child_pid=$!: Assign the PID of the child process to the variable child_pid for subsequent management (such as terminating the process).

 child_pid=$!

 # Capture the exit signal (such as Ctrl+C) and clean up the background process
 #trap "..." SIGINT SIGTERM: Captures SIGINT (Ctrl+C signal) and SIGTERM (terminal signal) and executes commands in quotes.
 #kill $main_pid $child_pid: Terminates the main process and child process.

 trap "kill $main_pid $child_pid; exit" SIGINT SIGTERM


 # Keep the script running
 #wait: Wait for all background processes to complete.  Since the main process and child process are infinitely looped, wait will block until the script receives a termination signal (such as Ctrl+C)
 wait