Notes: Files and Directories, Disk Usage, Inodes and Symlinks, Finding Files
Check your understanding of paths, file manipulation, globbing, rsync, disk usage, quotas, inodes, links and finding files.
-
notes/file_name.txt -
./notes/file_name.txt -
../user/notes/file_name.txt -
/home/user/notes/file_name.txt
Explanation: An absolute path starts at the root directory
/, so it points to the same place no matter where you are. The others are relative paths resolved from the current working directory.
Q. Your current directory is /home/user/Documents. Which relative path refers to /home/user/notes/todo.txt?
-
../notes/todo.txt -
./notes/todo.txt -
notes/todo.txt -
../../notes/todo.txt
Explanation:
..moves up one level to/home/user, andnotes/todo.txtcontinues from there.notes/...and./notes/...look insideDocuments, and../..climbs too far, to/home.
Q. How can you recognize a hidden file in a Linux directory listing?
- It has no read permission for others
- It is owned by the root user
- Its name begins with a dot (
.) - It is stored under
/tmp
Explanation: By convention any file whose name starts with
.(such as.bashrc) is hidden from a plainls. Permissions and ownership have nothing to do with it;ls -areveals these files.
Q. Which command lists all files, including hidden ones, in long format with permissions, owner and size?
-
ls -l -
ls -al -
ls -a -
ls -lh
Explanation:
-aincludes entries starting with a dot and-lgives the long format.ls -lalone hides dotfiles, andls -lhonly changes how sizes are printed.
Q. mkdir projects/2024/q1 fails with "No such file or directory" because projects does not exist yet. Which command creates the whole path?
-
mkdir -p projects/2024/q1 -
mkdir -r projects/2024/q1 -
mkdir -m 755 projects/2024/q1 -
touch projects/2024/q1
Explanation:
-pcreates every missing parent directory and does not complain if the path already exists.mkdirhas no-roption,-monly sets the mode, andtouchcreates files, not directories.
-
cpskips it with a message that-rwas not specified - The directory and all its contents are copied to
/backup/project - Only the files at the top level of
projectare copied - An empty directory named
projectis created in/backup
Explanation: Without
-r(or-a), GNUcprefuses to copy directories and prints-r not specified; omitting directory 'project'. Usecp -r project /backup/to copy the whole tree.
Q. Which cp command copies the directory project recursively while preserving permissions, timestamps and symbolic links?
-
cp -r project /backup/ -
cp -v project /backup/ -
cp -i project /backup/ -
cp -a project /backup/
Explanation:
-a(archive) recurses and preserves mode, ownership, timestamps and symlinks.-rrecurses but gives the copies new timestamps and the copying user's ownership,-vonly prints progress, and-ionly prompts before overwriting.
Q. Which command copies file.txt into /backup/ but asks for confirmation before overwriting an existing file?
-
cp -i file.txt /backup/ -
cp -f file.txt /backup/ -
cp -p file.txt /backup/ -
cp -u file.txt /backup/
Explanation:
-i(interactive) prompts before overwriting.-fforces the copy,-ppreserves mode and timestamps, and-ucopies only when the source is newer, none of which ask first.
- Renames the file
- Copies the file and keeps both names
- Fails because
mvonly moves files between directories - Creates a hard link called
newname.txt
Explanation:
mvboth moves and renames. Within one filesystem it just changes the directory entry, so the data and inode stay the same andoldname.txtno longer exists afterwards.
-
rm old_logs -
rmdir old_logs -
rm -r old_logs -
rm -r old_logs/*
Explanation:
rm -rrecurses into the directory and deletes it with its contents. Plainrmrefuses to remove directories,rmdironly removes empty ones, andold_logs/*leaves the directory itself (and its hidden files) behind.
- It makes
rmdescend into subdirectories - It moves the files to a trash folder instead of deleting them
- It overwrites the file data before deleting it
- It never prompts and ignores files that do not exist
Explanation:
-f(force) suppresses confirmation prompts and errors about missing files. Recursion comes from-r;rmhas no trash and does not securely erase data, which is whyrm -rfmust be used with care.
touch file{1..4}{a..f}- 10
- 4
- 6
- 24
Explanation: Brace expansion produces every combination: 4 numbers times 6 letters gives 24 names,
file1athroughfile4f, andtouchcreates each one.
cp config.yml{,.bak}- It fails, because a brace list cannot contain an empty item
- It copies
config.ymland a file named.bakinto the current directory - It copies
config.ymlto a new file namedconfig.yml.bak - It creates a directory
config.ymlthat contains.bak
Explanation: Brace expansion runs before
cpand turns the word intoconfig.yml config.yml.bak(empty item, then.bak), socpreceives a source and a destination. It is a common shortcut for making a backup copy.
echo {A,B{1..3},C}-
A B1 B2 B3 C -
A B1 C B2 B3 -
A B C 1 2 3 -
AB1C AB2C AB3C
Explanation: The inner range
{1..3}expands with the prefixBtoB1 B2 B3, and those words sit in the outer list betweenAandC.
Q. In a directory containing file.txt, file1.txt and file12.txt, which files does ls file?.txt list?
- Only
file1.txt -
file.txtandfile1.txt -
file1.txtandfile12.txt - All three files
Explanation: In a glob,
?matches exactly one character.file.txthas none in that position andfile12.txthas two, so onlyfile1.txtmatches. In a regular expression, by contrast,?means "zero or one of the preceding element".
-
file3.txt -
file12.txt -
file_1.txt -
file2.txt
Explanation:
[12]matches a single character that is either1or2.file12.txtwould need two characters in that position, and3or_are not in the set.
Q. In Bash with default settings, what does echo *.txt print in a directory that contains no .txt files?
- An empty line
- An error saying no files were found
- The literal text
*.txt - The names of all files in the directory
Explanation: Globs only match existing files. When nothing matches, Bash leaves the pattern unchanged (unless
nullgloborfailglobis set), soechoprints*.txt. Brace expansion, by contrast, always generates its words.
Q. A directory contains .env, a.txt and b.log. In Bash with default settings, what does echo * print?
-
.env a.txt b.log -
* -
.env -
a.txt b.log
Explanation: A leading dot must be matched explicitly, so
*skips hidden files (unlessdotglobis set). That is also whyrm -r dir/*leaves dotfiles behind;.*would match.env.
- Scrolls forward one line
- Scrolls forward one full screen
- Scrolls back one screen
- Jumps to the next search match
Explanation: Enter advances one line and Space advances one page. Moving backward is limited in
more(bworks only on files, not pipes), whilelesssupports full navigation in both directions.
Q. While reading a log in less, which keys search backward from the current position for the text ERROR?
-
/ERROR -
:ERROR -
?ERROR -
bERROR
Explanation: In
less,/patternsearches forward and?patternsearches backward;nrepeats the last search.bscrolls back one page and is not a search command.
- It shows one screen at a time and lets you scroll backward and search
- It compresses the file so it loads faster
- It shows only the last 10 lines of the file
- It lets you edit the file in place
Explanation:
catdumps the whole file to the terminal at once.lesspages the content, supports backward movement and/patternsearches, and does not modify the file.
- The first 2 lines of
a.txtfollowed by those ofb.txt, with no separator - Only the first 2 lines of
a.txt, because the second name is ignored - An error, because
headaccepts only one file at a time - The first 2 lines of each file, each block preceded by a
==> name <==header
Explanation: With several files,
head(andtail) prints a header line such as==> a.txt <==before each file's lines. Without-nthe default is 10 lines;-qsuppresses the headers.
- Every line from line 2 to the end, skipping the header line
- The last 2 lines of the file
- Only line 2 of the file
- The file with every second line removed
Explanation: A leading
+makestailstart output at that line number instead of counting from the end. It is a common way to drop a CSV header.
tail -n +50 data.csv | head -n 11- Lines 39 to 50
- Lines 50 to 61
- Lines 50 to 60
- The last 50 lines, then the first 11 lines
Explanation:
tail -n +50starts output at line 50 andhead -n 11keeps the next 11 lines, which are lines 50 through 60.
Q. The directory dest/ already exists. After running rsync -a src dest/ (no trailing slash on src), where does the file src/f1 end up?
-
dest/src/f1 -
dest/f1 -
dest/src/src/f1 - Nowhere;
rsyncrequires a trailing slash on a directory source
Explanation: Without a trailing slash,
rsynccopies the directory itself into the destination.rsync -a src/ dest/copies only the contents ofsrc, so the file would land atdest/f1.
Q. Which command makes /dest/ an exact mirror of /src/, removing files that no longer exist in the source?
-
rsync -az /src/ /dest/ -
rsync -a --dry-run /src/ /dest/ -
rsync -a --delete /src/ /dest/ -
rsync -aP /src/ /dest/
Explanation:
--deleteremoves destination files that are absent from the source. Without itrsynconly adds and updates files;--dry-runchanges nothing and-Ponly shows progress.
- Copies only files whose checksums differ
- Shows what would be transferred without changing anything
- Transfers files without compression
- Deletes extra files in the destination
Explanation: A dry run simulates the transfer and lists the actions (add
-vto see them). It is a good habit before a run that uses--delete.
-
-z -
-a -
-v -
-n
Explanation:
-zcompresses data in transit, which helps over slow links such as SSH to a remote host.-ais archive mode,-vis verbose and-nis a dry run.
Q. A large rsync transfer keeps getting interrupted. Which option shows per-file progress and keeps partially transferred files so the next run can resume?
-
-z -
--delete -
--exclude -
-P
Explanation:
-Pcombines--progressand--partial, so you can watch each file and avoid restarting large files from zero after an interruption.
- It always compresses files stored on the destination
- It can copy files that
cpis not permitted to read - It keeps old versions of every changed file
- It skips files that are already up to date at the destination
Explanation:
rsynccompares source and destination (by size and modification time by default) and transfers only what changed, so later runs are much faster. It does not bypass permissions or keep version history by itself.
-
dfcounts files, whileducounts directories -
dfreports usage per filesystem, whiledusums the given files and directories -
dfreads only/, whiledureads every mounted filesystem -
dfreports memory usage, whiledureports disk usage
Explanation:
dfasks each mounted filesystem for its size, used and available space.duwalks a directory tree and adds up what the files occupy, which is how you find space hogs.
Q. Which command prints a human-readable size summary for each file and directory in the current directory?
-
df -h . -
du -sh * -
ls -h -
du -h /
Explanation:
du -sgives one total per argument and-huses K, M and G units; the glob passes each non-hidden item as an argument.df -h .reports the whole filesystem, not individual items.
Q. When running du on /, which option keeps it from descending into other mounted filesystems such as /proc or a network share?
-
-s -
-a -
-x -
-c
Explanation:
-x(--one-file-system) skips directories on different filesystems.-ssummarizes,-alists files too and-cprints a grand total.
-
sort -ncannot read tab-separated input -
sort -his faster on large inputs -
sort -nsorts in reverse order by default -
sort -nignores unit suffixes, so it treats900Kas larger than2.0G
Explanation:
-ncompares only the leading number (900 versus 2.0).-hunderstands human-readable suffixes, sodu -sh * | sort -hrcorrectly lists the largest items first.
Q. Creating a file fails with "No space left on device", yet df -h shows the filesystem only 40% full. What should you check next?
-
free -h, because RAM may be full -
df -i, because the filesystem may have run out of inodes -
du -sh /tmp, because temporary files are not counted bydf -
ls -l, because the directory may be read-only
Explanation: Every file needs an inode. On filesystems with a fixed inode count, such as ext4, millions of tiny files can use them all while blocks remain free.
df -ishows inode usage.
Q. You delete a 10 GB log file with rm, but df shows no space was freed. What is the most likely reason?
- A running process still has the file open
-
rmonly removes the filename after a reboot -
dfcaches its results for an hour - Log files are always stored in a reserved area
Explanation:
rmremoves the name, but the inode and data are kept until every open file descriptor is closed.lsof +L1lists such deleted-but-open files; restarting the process that writes the log releases the space.
- The soft limit applies to inodes and the hard limit applies to blocks
- The soft limit applies to groups and the hard limit applies to users
- The soft limit can be exceeded for a grace period; the hard limit can never be exceeded
- The soft limit only produces log entries and is never enforced
Explanation: A user above the soft limit gets a grace period (set with
edquota -t) before writes are refused. The hard limit is an absolute ceiling. Both block and inode limits have soft and hard values.
Q. Which mount options must be added to an ext4 filesystem's /etc/fstab entry to enable user and group quotas?
-
quota=on -
usrquota,grpquota -
uquota,acl -
limits
Explanation: After adding
usrquota,grpquotaand remounting,quotacheck -cugcreates the quota files andquotaonstarts enforcement.uquotais XFS's spelling for user quotas, andaclenables access control lists, not quotas.
-
quota -u alice -
repquota alice -
quotaon alice -
edquota -u alice
Explanation:
edquotaedits limits.quota -uonly displays a user's usage,repquotareports on all users of a filesystem, andquotaonturns enforcement on for a filesystem.
- bob has exceeded both his block and inode hard limits
- bob's block usage is over its soft limit, but his file count is not
- bob's block quota is disabled, but his inode quota is enabled
- bob is under every limit and his grace period was reset
Explanation: The first character refers to block limits and the second to inode (file) limits;
+means usage is above the soft limit. bob can keep writing until he hits the hard limit or the grace period shown in the grace column expires.
- The file's permissions
- The owner's UID
- The filename
- The modification time
Explanation: A directory entry maps a name to an inode number; the inode holds the metadata and data block pointers but not the name. That is why one inode can have several names (hard links).
-
ls -n -
ls -li -
ls -s -
ls -F
Explanation:
-iprints inode numbers, and-ladds the long listing.-nshows numeric UIDs and GIDs,-sshows allocated blocks and-Fappends type indicators.
- When its inode metadata (or content) last changed
- When the file was created
- When the file was last read
- When the file was last copied
Explanation:
ctimeis the status change time, updated by changes such aschmod,chownor writing to the file. It is not creation time; reads updateatimeand content changes updatemtime.
- It becomes a broken link
- It still works and shows the same content
- It is deleted as well
- It becomes an empty file
Explanation: Without
-s,lncreates a hard link, a second name for the same inode. The data is kept until the last name is removed, socopy.txtis unaffected.
Q. You create a new file report.txt and then run ln report.txt copy.txt. What link count does stat report.txt show?
- 0
- 1
- 2
- 3
Explanation: The inode now has two directory entries pointing at it, so its link count is 2. A symlink would not change the target's link count.
- The same inode number for both names, and a link count of 2
- Different inode numbers, and
a.txtstill has a link count of 1 - The same inode number, with
linkmarked by anltype - Only
a.txt, because symlinks have no inode of their own
Explanation: A symlink is a separate small file with its own inode that stores the path
a.txt. It adds no directory entry for the target's inode, so the target's link count is unchanged.
- Hard links require root privileges
- Hard links only work within one directory
- USB drives do not support links of any kind
- Inode numbers are only meaningful within one filesystem
Explanation: A hard link is a directory entry pointing at an inode number, and those are unique only within a filesystem, so
lnfails with "Invalid cross-device link". A symbolic link, which stores a path, works instead.
-
dir2becomes a second name fordir1 -
lnrefuses, because hard links to directories are not allowed -
dir2is created as a symbolic link todir1 -
dir1is copied recursively todir2
Explanation: GNU
lnprints "hard link not allowed for directory". Directory hard links could create loops in the tree and confuse..and tools that walk it; useln -s dir1 dir2for a second path to a directory.
- The symlink is deleted automatically
- The symlink keeps a copy of the target's data
- The symlink remains but is dangling and fails when accessed
- The system refuses to delete the target
Explanation: A symlink stores only a path. Once nothing exists at that path, opening the link gives "No such file or directory", although the link itself is still listed.
Q. The symlink /opt/app/current stores the relative target releases/v2. Where does the system look for that target?
- In the current working directory of the process using the link
- In
/opt/app, the directory that contains the symlink - In the user's home directory
- In
/, the root directory
Explanation: Relative symlink targets are resolved from the directory containing the link, so this one points to
/opt/app/releases/v2no matter where you run commands from.
Q. Which command prints the fully resolved, canonical absolute path that the symlink mylink points to?
-
readlink mylink -
readlink -f mylink -
ls -i mylink -
stat -L mylink
Explanation:
readlink -ffollows every link in the chain and prints an absolute path. Plainreadlinkprints the stored target text, which may be relative, andstat -Lshows the target's metadata rather than its path.
Q. The symlink mylink currently points to fileA.txt. Which command makes it point to fileB.txt instead?
-
ln -s fileB.txt mylink -
ln fileB.txt mylink -
ln -sfn fileB.txt mylink -
readlink -f fileB.txt mylink
Explanation: A symlink cannot be edited in place.
-freplaces the existing link and-nstopslnfrom descending intomylinkif it points to a directory. Without-f,lnfails with "File exists".
-
find /var -name "*.log" -mtime +7 -
find /var -name "*.log" -atime -7 -
find /var -name "*.log" -mmin -7 -
find /var -name "*.log" -mtime -7
Explanation:
-mtime -7means modified less than 7 days ago;+7means more than 7 days ago.-atimechecks access time and-mmincounts minutes, not days.
- Files created after
file2was first created - Regular files modified more recently than
file2 - Files that are larger than
file2 - Files with a higher inode number than
file2
Explanation:
-newercompares modification times against the reference file. Adding-type frestricts results to regular files.
- Files larger than 2000 bytes
- Files larger than 2000 KiB
- Files using more than 2000 blocks of 512 bytes (about 1 MB)
- Files containing more than 2000 lines
Explanation: A
-sizenumber without a suffix counts 512-byte blocks, rounded up. Suffixes change the unit, for example-size +10Mfor more than 10 MiB orcfor bytes.
-
find . -name "*.bak" -delete -
find . -name "*.bak" -exec rm {} \; -
find . -name "*.bak" -ok rm {} \; -
find . -name "*.bak" -print -delete
Explanation:
-okworks like-execbut prompts before each command and runs it only on ayanswer.-deleteand-exec rmremove matches without asking.
-
locateonly searches the current directory -
locateneeds the-ioption for exact names -
locateignores files owned by regular users -
locatesearches a prebuilt database that has not been updated yet
Explanation:
locateis fast because it queries a database built byupdatedb, which usually runs periodically. Newly created files appear after the next update;findsearches the live filesystem.
Q. In Bash, ls is an alias for ls --color=auto. Which command shows the alias as well as every ls executable found in PATH?
-
which ls -
type -a ls -
locate -b ls -
which -a ls
Explanation:
typeis a shell builtin, so it knows about aliases, functions and builtins, and-alists every match.whichis an external program that only searchesPATHfor files, even with-a.