Unit2 - Subjective Questions
CSC202 • Practice Questions with Detailed Answers
Explain the significance of the Read, Write, and Execute permissions when applied to a file compared to when they are applied to a directory in Linux.
In Linux, standard permissions (r, w, x) behave differently depending on whether the target is a file or a directory:
1. Read (r)
- For Files: Allows the contents of the file to be opened and read (e.g., using
cator a text editor). - For Directories: Allows the user to list the contents of the directory (e.g., using
ls). However, without execute permission, metadata details cannot be accessed.
2. Write (w)
- For Files: Allows the user to modify the file's contents (save changes). It does not automatically allow deleting the file (that depends on the parent directory's permissions).
- For Directories: Allows the user to create, delete, and rename files within that directory. This is a powerful permission as it allows deleting files even if the user does not have write permission on the file itself.
3. Execute (x)
- For Files: Allows the file to be run as a program or script.
- For Directories: Allows access to enter (cd) the directory and access files/inodes within it. Without this, you cannot enter the directory even if you have read permissions.
Describe how to change file permissions using the chmod command with the Octal (Numeric) method. Provide examples for setting specific permission sets.
The chmod command changes file mode bits. In the Octal method, permissions are represented by numbers:
- Read (r) = 4
- Write (w) = 2
- Execute (x) = 1
- No permission = 0
The sum of these numbers represents the permission set for the User (u), Group (g), and Others (o).
Syntax: chmod [octal_value] filename
Examples:
-
Full Permissions for User, Read/Execute for Group/Others:
- User:
- Group:
- Others:
- Command:
chmod 755 filename
-
Read/Write for User, Read-only for Group, No access for Others:
- User:
- Group: $4$
- Others: $0$
- Command:
chmod 640 filename
What is the umask in Linux? Calculate the default file and directory permissions if the umask is set to 022.
Definition: umask (User File Creation Mode Mask) determines the default permissions assigned to newly created files and directories. It works by subtracting permissions from the system base default.
Base Defaults:
- Files: 666 (rw-rw-rw-) — Files are not created with execute permissions by default for security.
- Directories: 777 (rwxrwxrwx)
Calculation for umask 022:
-
For Directories:
- Base: $777$
- Umask: $022$
- Result:
- Permissions: User (rwx), Group (r-x), Others (r-x).
-
For Files:
- Base: $666$
- Umask: $022$
- Result:
- Permissions: User (rw-), Group (r--), Others (r--).
Explain the three Special Permissions in Linux: SUID, SGID, and the Sticky Bit. Include their numeric values and symbolic representation.
Special permissions provide additional functionality beyond standard rwx.
1. Set User ID (SUID)
- Function: When applied to an executable file, it runs with the permissions of the file owner rather than the user who executes it (e.g.,
passwdcommand). - Symbolic: Appears as an
sin the user execute position (e.g.,rwsr-xr-x). - Numeric Value: 4000
2. Set Group ID (SGID)
- Function on Files: Runs with the permissions of the file's group.
- Function on Directories: New files created inside inherit the directory's group ownership, not the creator's primary group. Used for shared folders.
- Symbolic: Appears as an
sin the group execute position (e.g.,rwxr-sr-x). - Numeric Value: 2000
3. Sticky Bit
- Function: Applied to directories (like
/tmp). Ensures that only the file owner, directory owner, or root can delete or rename files within that directory, preventing users from deleting each other's files. - Symbolic: Appears as a
tin the others execute position (e.g.,rwxrwxrwt). - Numeric Value: 1000
Distinguish between Hard Links and Soft (Symbolic) Links in the Linux file system.
Hard Links and Soft Links are methods to reference files, but they function differently:
| Feature | Hard Link | Soft (Symbolic) Link |
|---|---|---|
| Mechanism | Points directly to the inode of the original file. | Points to the path/filename of the original file. |
| Inode Number | Shares the same inode number as the original. | Has a different, unique inode number. |
| Cross-Filesystem | Cannot span across different file systems (partitions). | Can link to files on different file systems. |
| Directory Linking | Generally not allowed (to prevent loops). | Can link to directories. |
| Deleting Original | The link remains valid and content is accessible (until the link count is 0). | The link becomes "broken" (dangling) and points to nothing. |
| Command | ln target linkname |
ln -s target linkname |
What are Access Control Lists (ACLs)? Explain how to view and set ACLs using getfacl and setfacl.
Access Control Lists (ACLs) provide a more flexible permission mechanism than the standard User-Group-Others model. They allow assigning permissions to specific individual users or groups that are not the owner or the primary group.
1. Viewing ACLs (getfacl):
Displays the file name, owner, group, and the Access Control List.
- Syntax:
getfacl filename - Output: Shows lines like
user:alice:rw-indicating specific user permissions.
2. Setting ACLs (setfacl):
Used to modify the ACL entries.
- Syntax:
setfacl -m [u/g]:[name]:[perms] filename - Example: Give user 'bob' read and write access to 'file.txt':
setfacl -m u:bob:rw file.txt - Remove ACL:
setfacl -x u:bob file.txt - Remove all ACLs:
setfacl -b file.txt
Explain the purpose of the following key directories in the Filesystem Hierarchy Standard (FHS): /etc, /var, /home, /bin, and /dev.
The FHS defines the directory structure of Linux:
- /etc: Contains system-wide configuration files and shell scripts used to boot the system. No binary programs should be stored here (e.g.,
/etc/passwd,/etc/ssh/sshd_config). - /var: Contains variable data files that change while the system is running. This includes log files (
/var/log), spool files for printers/mail (/var/spool), and temporary files preserved between reboots. - /home: Contains the home directories for all regular users. Personal files, settings, and documents are stored here (e.g.,
/home/john). - /bin: Contains essential user binary executables (programs) required for booting and repairing the system in single-user mode (e.g.,
ls,cp,cat). - /dev: Contains special device files that represent hardware components (e.g.,
/dev/sdafor hard drive,/dev/ttyfor terminals).
What is an Inode? List the information stored within an inode.
Definition: An inode (Index Node) is a data structure on a Linux filesystem that stores all the metadata about a file except its name and its actual data content.
Information Stored in an Inode:
- File Type: (Regular file, directory, link, etc.)
- Permissions: (Read, Write, Execute for U/G/O)
- Ownership: User ID (UID) and Group ID (GID)
- File Size: Size in bytes.
- Timestamps: Access time (atime), Modification time (mtime), and Change time (ctime).
- Link Count: Number of hard links pointing to the inode.
- Data Block Pointers: Addresses of the physical disk blocks where the file content is stored.
Explain the usage of the find command. Provide command examples to find files based on name, size, and modification time.
The find command searches for files in a directory hierarchy based on various criteria.
Syntax: find [path] [options] [expression]
Examples:
-
Find by Name:
- Find all files named "report.txt" in the /home directory.
find /home -name "report.txt"- (Use
-inamefor case-insensitive search).
-
Find by Size:
- Find files larger than 100MB in the current directory.
find . -size +100M
-
Find by Modification Time:
- Find files modified in the last 7 days in /var/log.
find /var/log -mtime -7
-
Find by Type:
- Find only directories inside /tmp.
find /tmp -type d
Compare the locate command with the find command regarding speed and accuracy.
1. Locate:
- Mechanism: Searches a pre-built database (
mlocate.db) of files on the system. - Speed: Extremely fast, as it reads a database file rather than scanning the hard drive.
- Accuracy: Can be inaccurate (outdated). If a file was created recently but the database hasn't been updated (usually via
updatedb),locatewon't find it. Conversely, it might list deleted files.
2. Find:
- Mechanism: Scans the live file system hierarchy in real-time.
- Speed: Slower, especially for large file systems, as it traverses directories physically.
- Accuracy: Always accurate. It reflects the current state of the file system immediately.
Describe the three modes of operation in the vi/vim editor. How do you switch between them?
Vim operates in three primary modes:
1. Command Mode (Normal Mode):
- Purpose: The default mode for navigation, copying, deleting, and pasting text. Keys act as commands.
- Entry: Press
Escfrom any other mode. - Actions:
x(delete char),dd(delete line),yy(copy line),p(paste).
2. Insert Mode:
- Purpose: Used for typing and editing text content.
- Entry: From Command mode, press
i(insert before cursor),a(append after cursor), oro(open new line below). - Exit: Press
Escto return to Command Mode.
3. Last Line Mode (Ex Mode):
- Purpose: Used for saving files, exiting, searching, and configuring the environment.
- Entry: From Command mode, press
:(colon). - Actions:
:w(save),:q(quit),:wq(save and quit),:q!(force quit without saving),/pattern(search).
Explain the function of the chown and chgrp commands with syntax examples.
1. chown (Change Owner):
- Purpose: Changes the user ownership (and optionally group ownership) of a file or directory.
- Syntax:
chown [new_owner] [filename] - Combined Syntax:
chown [user]:[group] [filename] - Example:
chown alice report.txt(Changes owner to alice).chown alice:developers report.txt(Changes owner to alice and group to developers). - Recursive:
chown -R alice /data(Applied to directory and contents).
2. chgrp (Change Group):
- Purpose: Changes only the group ownership of a file or directory.
- Syntax:
chgrp [new_group] [filename] - Example:
chgrp managers sales_data.txt - Recursive:
chgrp -R managers /data/sales
What are Wildcards (Globbing) in Linux? Explain the usage of *, ?, and [].
Wildcards (file globbing) are special characters used by the shell to match patterns of filenames.
-
*Asterisk (``):**
- Matches zero or more characters.
- Example:
ls *.txtlists all files ending in .txt.rm data*removes all files starting with "data".
-
Question Mark (
?):- Matches exactly one arbitrary character.
- Example:
ls file?.txtmatchesfile1.txt,fileA.txt, but notfile10.txt.
-
Square Brackets (
[]):- Matches one character from a specified range or set.
- Example:
ls file[1-3].txtmatchesfile1.txt,file2.txt, andfile3.txt.ls [Aa]*.txtmatches files starting with A or a.
Explain the usage of the ls command. Describe the output and purpose of the options -l, -a, -h, and -R.
The ls command lists directory contents.
-
ls -l(Long Listing):- Displays detailed information including permissions, link count, owner, group, size (in bytes), modification date, and filename.
- Example Output:
-rw-r--r-- 1 user group 4096 Jan 1 12:00 file.txt
-
ls -a(All):- Shows all files, including hidden files (those starting with a dot
.), such as.bashrc.
- Shows all files, including hidden files (those starting with a dot
-
ls -h(Human Readable):- Must be used with
-lor-s. Converts file sizes from bytes to KB, MB, GB (e.g., shows4.0Kinstead of4096).
- Must be used with
-
ls -R(Recursive):- Lists the contents of the current directory and all subdirectories recursively.
How does the grep command work? Provide examples for case-insensitive search and recursive search within directories.
grep (Global Regular Expression Print) searches for a specific string or pattern within text files and outputs the lines containing the match.
Basic Syntax: grep [pattern] [file]
Common Options & Examples:
-
Standard Search:
grep "error" /var/log/syslog(Prints lines containing "error").
-
Case-Insensitive Search (
-i):- Ignores case distinctions (matches "Error", "ERROR", "error").
grep -i "failed" auth.log
-
Recursive Search (
-ror-R):- Searches all files in the specified directory and its subdirectories.
grep -r "config" /etc/
-
Invert Match (
-v):- Prints lines that do not match the pattern.
grep -v "#" config.txt(Displays lines that are not comments).
Differentiate between cp, mv, and rm commands with respect to file management.
1. cp (Copy):
- Function: Creates a duplicate of the source file/directory at the destination. The original file remains unchanged.
- Syntax:
cp source destination - Flag: Use
-rto copy directories recursively.
2. mv (Move):
- Function: Moves a file/directory from one location to another. Also used for Renaming files if the destination is in the same directory but has a different name.
- Syntax:
mv source destination - Note: The original file is removed from the source location.
3. rm (Remove):
- Function: Deletes files or directories. In Linux, this is often permanent (no Recycle Bin via command line).
- Syntax:
rm filename - Flags:
-rfor directories,-fto force delete without confirmation.
Explain the purpose of head and tail commands. How can tail be used to monitor log files in real-time?
1. head:
- Purpose: Outputs the beginning part of files.
- Default: Shows the first 10 lines.
- Custom:
head -n 5 file.txt(Shows first 5 lines).
2. tail:
- Purpose: Outputs the end part of files.
- Default: Shows the last 10 lines.
- Custom:
tail -n 20 file.txt(Shows last 20 lines).
Real-time Monitoring (-f):
- Using the
-f(follow) option allows an administrator to view lines appended to a file in real-time. This is essential for troubleshooting logs. - Command:
tail -f /var/log/syslog - As new log entries are written by the system, they immediately appear on the screen.
What are file attributes in the context of the ls -l command? Break down the output string: drwxr-xr--.
The string drwxr-xr-- represents the file type and permission settings.
It is broken down into 4 parts (1 char + 3 sets of 3):
-
File Type (1st character):
d: Indicates this is a Directory.- (
-would indicate a regular file,la symbolic link).
-
User/Owner Permissions (Next 3 chars -
rwx):- r: Read enabled.
- w: Write enabled.
- x: Execute enabled.
- Interpretation: The owner can read, modify, and enter the directory.
-
Group Permissions (Next 3 chars -
r-x):- r: Read enabled.
- -: Write disabled.
- x: Execute enabled.
- Interpretation: Group members can list and enter the directory but cannot create/delete files in it.
-
Others Permissions (Last 3 chars -
r--):- r: Read enabled.
- -: Write disabled.
- -: Execute disabled.
- Interpretation: Everyone else can list the contents but cannot enter the directory or modify it.
Explain the Input/Output Redirection operators: >, >>, <, and 2>.
Redirection changes the source of input or the destination of output for commands.
-
Standard Output Redirection (
>):- Redirects output to a file, overwriting existing content.
ls > filelist.txt
-
Append Output Redirection (
>>):- Redirects output to a file, appending to the end of existing content.
date >> log.txt
-
Standard Input Redirection (
<):- Feeds the contents of a file into a command as input.
wc -l < file.txt(Counts lines in file.txt).
-
Standard Error Redirection (
2>):- Redirects error messages (File Descriptor 2) to a file instead of the screen.
ls /nonexistent_folder 2> errors.log
Describe the function of the wc, cut, and sort commands for managing text file content.
1. wc (Word Count):
- Counts newlines, words, and bytes in a file.
- Options:
-l(lines),-w(words),-c(bytes). - Example:
wc -l file.txtreturns the line count.
2. cut:
- Extracts specific sections from each line of a file.
- Options:
-d(delimiter),-f(field number). - Example:
cut -d ":" -f 1 /etc/passwdextracts the first field (usernames) separated by colons.
3. sort:
- Sorts lines of text files.
- Options:
-n(numeric sort),-r(reverse order),-u(unique, removes duplicates). - Example:
sort -n numbers.txtsorts a list of numbers in ascending order.