Linux Fundamentals¶
122 cards β π’ 50 easy | π‘ 47 medium | π΄ 10 hard
π’ Easy (50)¶
1. What command shows the current directory path?
Show answer
`pwd` (Print Working Directory) displays the absolute path of your current directory. Example output: `/home/user/projects`. Use `pwd -P` to resolve symlinks and show the physical path.Gotcha: in a symlinked directory, plain `pwd` may show the symlink path while `pwd -P` shows the real location.
2. Every command fails with command not found. How to trace the source of the error and resolve it?
Show answer
It looks that at one point or another are overwriting the default `PATH` environment variable. The type of errors you have, indicates that `PATH` does not contain e.g. `/bin`, where the commands (including bash) reside.One way to begin debugging your bash script or command would be to start a subshell with the `-x` option:
```bash\nbash --login -x\n```
This will show you every command, and its arguments, which is executed when starting that shell.
Also very helpful is show `PATH` variable values:
```bash\necho $PATH\n```
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
3. What is the cat command short for?
Show answer
Concatenate β `cat` is short for concatenate. Its primary purpose is joining multiple files end-to-end and writing the result to stdout, though it is most commonly used to display the contents of a single file.Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
4. How do I grep recursively?
Show answer
Use `grep -r` (or `grep -rn` to include line numbers). Examples: `grep -r 'pattern' /path/to/dir` searches all files recursively. `grep -rn 'TODO' .` shows matches with line numbers. `grep -rl 'pattern' .` lists only filenames.Remember: grep = Global Regular Expression Print. `-r` recursive, `-i` insensitive, `-n` line numbers.
Example: `grep -rn 'ERROR' /var/log/` β recursive with line numbers.
5. How do you find a text string in files on Linux?
Show answer
Using the grep command (e.g., grep "search_term" filename).Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
6. What command creates a new directory?
Show answer
`mkdir`. Use `-p` to create parent directories as needed (e.g., `mkdir -p /opt/app/logs`). Without `-p`, it errors if the parent doesn't exist.Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
7. What is /etc/skel in Linux and how is it used during user creation?
Show answer
`/etc/skel` is a skeleton directory whose contents are copied into new users' home directories when they are created with `useradd`.Remember: sed = Stream EDitor. `s/old/new/g` β s=substitute, g=global. `-i` = in-place.
Example: `sed -i 's/old/new/g' file.txt`. `-i.bak` creates backup first.
8. What command removes an empty directory?
Show answer
`rmdir`. It only removes empty directories β fails if the directory has contents. Use `rm -r` to recursively remove a directory and its contents.Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
9. You have to find all files larger than 20MB. How you do it?
Show answer
```bash\nfind / -type f -size +20M\n```Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
10. What does rm -rf do and why is it dangerous?
Show answer
Recursively and forcibly removes a directory and its contents.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
11. What is escaping? What escape character is used for?
Show answer
Escaping prevents the shell from interpreting special characters.The backslash (\) is the escape character:
- \$ - Literal dollar sign
- \\ - Literal backslash
-
- Newline (in echo -e)
- \" - Literal quote inside double quotes
Examples:
- echo \$HOME β $HOME (literal)
- echo "He said \"hello\"" β He said "hello"
- touch file\ name.txt β Creates "file name.txt"
Within single quotes, no escaping needed (all literal).
Within double quotes, escape \, $, `, ", !
Remember: sed = Stream EDitor. `s/old/new/g` β s=substitute, g=global. `-i` = in-place.
Example: `sed -i 's/old/new/g' file.txt`. `-i.bak` creates backup first.
12. What is the difference between man and info?
Show answer
`man` provides concise reference pages organized by sections (1=commands, 5=file formats, 8=admin). `info` provides longer, hyperlinked tutorials in a Texinfo format with navigation between nodes. In practice, most people use `man`. Some GNU tools (like `coreutils`) have more detailed `info` pages than their `man` pages.13. How do you create an empty file or update its timestamp?
Show answer
`touch`. Creates the file if it doesn't exist; updates atime/mtime if it does. Commonly used to create empty marker/lock files or trigger build systems.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
14. Where are repositories stored (based on the distribution)?
Show answer
Repository configuration locations:RHEL/Fedora/CentOS:
- /etc/yum.repos.d/*.repo
- Contains: baseurl, gpgcheck, enabled
- dnf config-manager --add-repo URL
Debian/Ubuntu:
- /etc/apt/sources.list
- /etc/apt/sources.list.d/*.list
- Format: deb URL distribution components
- add-apt-repository for PPAs
SUSE:
- /etc/zypp/repos.d/
- zypper addrepo
After changes:
- yum/dnf: Automatic refresh
- apt: apt update required
Remember: sed = Stream EDitor. `s/old/new/g` β s=substitute, g=global. `-i` = in-place.
Example: `sed -i 's/old/new/g' file.txt`. `-i.bak` creates backup first.
15. What does the ls command do in Linux?
Show answer
It lists directory contents (files and folders) in the current working directory.Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
16. How to check what is the hostname of the system?
Show answer
`cat /etc/hostname`You can also run `hostnamectl` or `hostname` but that might print only a temporary hostname. The one in the file is the permanent one.
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
17. How to find files that have been modified on your system in the past 60 minutes?
Show answer
```bash\nfind / -mmin -60 -type f\n```Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
18. How do you move up one directory level?
Show answer
`cd ..` β the double dot `..` is a special directory entry pointing to the parent. Every directory has it (even `/`, where `..` points to itself).Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
19. What command finds files by name in a directory tree?
Show answer
`find`. Examples: `find /var -name '*.log'` by name, `find / -size +100M` by size, `find . -mtime -1` modified in last day. Combine with `-exec` to act on results.Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
20. What is special about the /tmp directory when compared to other directories?
Show answer
`/tmp` folder is cleaned automatically, usually upon reboot.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
21. What is the difference between rm and rm -rf?
Show answer
`rm` only deletes the named files (and not directories). With `-rf` as you say:- `-r`, `-R`, `--recursive` recursively deletes content of a directory, including hidden files and sub directories
- `-f`, `--force` ignore nonexistent files, never prompt
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
22. How can I sync two local directories?
Show answer
To sync the contents of **dir1** to **dir2** on the same system, type:```bash\nrsync -av --progress --delete dir1/ dir2\n```
- `-a`, `--archive` - archive mode
- `--delete` - delete extraneous files from dest dirs
- `-v`, `--verbose` - verbose mode (increase verbosity)
- `--progress` - show progress during transfer
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
23. How do you view the first 10 lines of a file?
Show answer
`head`. By default shows first 10 lines. Use `-n 20` for 20 lines, or `-c 100` for first 100 bytes. Pairs with `tail` for viewing file ends.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
24. How would you check what is the size of a certain directory?
Show answer
`du -shRemember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
25. Many basic maintenance tasks require you to edit config files. Explain ways to undo the changes you make.
Show answer
- manually backup of a file before editing (with brace expansion like this: `cp filename{,.orig}`)- manual copy of the directory structure where file is stored (e.g. `cp`, `rsync` or `tar`)
- make a backup of original file in your editor (e.g. set rules in your editor configuration file)
- the best solution is to use `git` (or any other version control) to keep track of configuration files (e.g. `etckeeper` for `/etc` directory)
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
26. What is an incremental backup?
Show answer
An incremental backup is a type of backup that only copies files that have changed since the previous backup.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
27. How do you create a shortcut for a complex command in Bash?
Show answer
Add an alias to `~/.bashrc` (or `~/.zshrc` for zsh).Example: `alias k='kubectl'` or `alias ll='ls -la'`. Run `source ~/.bashrc` to activate immediately without restarting the shell. Use `alias` with no arguments to list all current aliases.
Gotcha: aliases defined in the shell are lost when the session ends unless saved to the rc file.
28. What is shell globbing and how does pattern matching work?
Show answer
Filename pattern matching by the shell before command execution.Patterns:
- * - Any characters (except leading dot)
- ? - Exactly one character
- [abc] - Any of a, b, c
- [a-z] - Range
- [!abc] - NOT listed
Examples:
- ls *.txt - All .txt files
- rm test[0-9].txt - test0.txt through test9.txt
Shell expands globs BEFORE passing to command.
Remember: *=any, ?=one char, [abc]=one of, {a,b}=expansion. Globs β regex.
29. What does cd ~ accomplish?
Show answer
It returns the user to their home directory.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
30. What is the # sign in a shell prompt usually indicative of?
Show answer
The `#` prompt indicates a superuser (root) session, while `$` indicates a regular user session. This convention is defined in the PS1 shell variable and is nearly universal across Linux distributions.Gotcha: running as root is dangerous β prefer `sudo` for individual commands to maintain an audit trail and limit exposure.
31. What is the purpose of the shebang (#!) at the start of a script?
Show answer
It specifies the interpreter for the script (e.g., #!/bin/bash tells the OS to run the script with the Bash shell).Remember: c=create, x=extract, t=list, v=verbose, f=file, z=gzip. "eXtract Ze File" = xzf.
Example: Create: `tar czf arch.tar.gz dir/` Extract: `tar xzf arch.tar.gz`
32. How do you list all files, including hidden ones?
Show answer
`ls -a`. The `-a` flag includes entries starting with `.` (dotfiles). `ls -la` combines long format with hidden files for the most complete listing.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
33. What is stored in each of the following paths?
Show answer
* binaries* configuration files
* home directories of the different users
* files that tend to change and be modified like logs
* temporary files
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
34. What are wildcards? Can you give an example of how to use them?
Show answer
Wildcards are special characters for pattern matching in filenames.Common wildcards:
- * - Matches zero or more characters
- ? - Matches exactly one character
- [...] - Matches any character in brackets
- [!...] - Matches any character NOT in brackets
Examples:
- ls *.log - All files ending in .log
- rm file?.txt - file1.txt, file2.txt, etc.
- cp [A-Z]*.pdf backup/ - PDFs starting with uppercase
- mv *[0-9].bak archive/ - Files ending with digit.bak
Wildcards are expanded by shell before command execution.
Remember: *=any, ?=one char, [abc]=one of, {a,b}=expansion. Globs β regex.
35. You run ls and you get "/lib/ld-linux-armhf.so.3 no such file or directory". What is the problem?
Show answer
The ls executable is built for an incompatible architecture.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
36. What is the difference between these two commands? Will it result in the same output?
Show answer
The echo command receives two separate arguments in the first execution and in the second execution it gets one argument which is the string "hello world". The output will be the same.Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
37. How do you list the content of a package without actually installing it?
Show answer
Depends on package format:RPM:
- rpm -qlp package.rpm - List files in .rpm
- rpm -ql package-name - List files of installed package
- repoquery -l package - Query from repo
DEB:
- dpkg -c package.deb - List files in .deb
- dpkg -L package-name - List installed package files
- apt-file list package - From repo
Other info:
- rpm -qip package.rpm - Package info
- dpkg -I package.deb - Package info
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
38. How to know to which package a file on the system belongs?
Show answer
Query package databases:RPM (RHEL/Fedora):
- rpm -qf /path/to/file
- Example: rpm -qf /bin/ls β coreutils
DEB (Debian/Ubuntu):
- dpkg -S /path/to/file
- Example: dpkg -S /bin/ls β coreutils
If file not from package:
- Commands return "not owned by any package"
- File was manually created or from source install
Search for files not yet installed:
- yum provides /path (or dnf)
- apt-file search /path
Remember: which=PATH, whereis=binary+man+src, type=alias/builtin/file. type is best.
39. What is the difference between single and double quotes?
Show answer
In bash, quotes affect variable and special character handling:Single quotes ('...'):
- Everything is literal
- No variable expansion
- No special character interpretation
- echo '$HOME' prints: $HOME
Double quotes ("..."):
- Variables are expanded
- Command substitution works
- Special chars \, $, `, ! interpreted
- echo "$HOME" prints: /home/user
Backticks/$(...)
- Command substitution
- Output replaces the expression
Example:
- name="world"
- echo 'Hello $name' β Hello $name
- echo "Hello $name" β Hello world
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
40. What do the fields in ls -al output mean?
Show answer
In the order of output:```bash\n-rwxrw-r-- 1 root root 2048 Jan 13 07:11 db.dump\n```
- file permissions,
- number of links,
- owner name,
- owner group,
- file size,
- time of last modification,
- file/directory name
File permissions is displayed as following:
- first character is `-` or `l` or `d`, `d` indicates a directory, a `-` represents a file, `l` is a symlink (or soft link) - special type of file
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
41. How is a userβs default group determined? How would you change it?
Show answer
```bash\nuseradd -m -g initial_group username\n````-g/--gid`: defines the group name or number of the user's initial login group. If specified, the group name must exist; if a group number is provided, it must refer to an already existing group.
If not specified, the behaviour of useradd will depend on the `USERGROUPS_ENAB` variable contained in `/etc/login.defs`. The default behaviour (`USERGROUPS_ENAB yes`) is to create a group with the same name as the username, with **GID** equal to **UID**.
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
42. What is the result of running the following command? yippiekaiyay 1>&2 die_hard
Show answer
An output similar to: `yippikaiyay: command not found...`The file `die_hard` will not be created
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
43. How can you check what is the path of a certain command?
Show answer
`whichExample: `type ls` might show it is aliased to `ls --color=auto`. Use `type` as your default lookup.
44. What is the .bashrc file?
Show answer
A script executed when a new interactive shell starts.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
45. What is a Linux "package manager"?
Show answer
It's a tool to install, update, and manage software packages (examples: apt on Debian/Ubuntu, yum or dnf on Red Hat/Fedora).Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
46. How do you view the last 10 lines of a file?
Show answer
`tail`. By default shows last 10 lines. `tail -f` follows the file in real-time (great for watching logs). `tail -n 50` shows last 50 lines.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
47. How do you search for a specific string within a file?
Show answer
`grep`. Examples: `grep -r 'error' /var/log/` recursive search, `grep -i` case-insensitive, `grep -c` count matches, `grep -n` show line numbers. Supports regex with `-E`.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
48. Execute combine multiple shell commands in one line.
Show answer
If you want to execute each command only if the previous one succeeded, then combine them using the `&&` operator:```bash\ncd /my_folder && rm *.jar && svn co path to repo && mvn compile package install\n```
If one of the commands fails, then all other commands following it won't be executed.
If you want to execute all commands regardless of whether the previous ones failed or not, separate them with semicolons:
```bash\ncd /my_folder; rm *.jar; svn co path to repo; mvn compile package install\n```
49. How do you get help on the command line?
Show answer
- `man` [commandname] can be used to see a description of a command (ex.: `man less`, `man cat`)- `-h` or `--help` some programs will implement printing instructions when passed this parameter (ex.: `python -h` and `python --help`)
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
50. What does tail -f do?
Show answer
`tail -fExample: `tail -f /var/log/syslog`. Use `tail -F` to also handle file rotation (log files that get renamed and recreated). Alternative: `less +F
π‘ Medium (47)¶
1. How to generate a random string of 7 characters?
Show answer
`mkpasswd -l 7`Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
2. How to rename the name of a file or a directory?
Show answer
Using the `mv` command.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
3. What are soft limits and hard limits?
Show answer
**Hard limit** is the maximum allowed to a user, set by the superuser or root. This value is set in the file `/etc/security/limits.conf`. The user can increase the **soft limit** on their own in times of needing more resources, but cannot set the **soft limit** higher than the **hard limit**.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
4. Create a file with 100 lines with random values.
Show answer
For example:```bash\ncat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 100 > /path/to/file\n```
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
5. What happens when you execute ls -l *.log?
Show answer
The shell expands *.log before ls runs:1. Shell glob expansion:
- Shell finds all files matching *.log
- Replaces *.log with list of filenames
- ls sees: ls -l file1.log file2.log file3.log
2. If no matches:
- Default: literal "*.log" passed to ls
- With nullglob: empty string (no argument)
- ls may error or show nothing
3. ls execution:
- Receives expanded filenames
- Calls stat() on each file
- Displays long format info
Key point: Glob expansion happens in shell, not in ls.
- ls never sees the asterisk
- Shell does pattern matching before exec
6. Explain each field in the output of ls -l command
Show answer
It shows a detailed list of files in a long format. From the left:* file permissions, number of links, owner name, owner group, file size, timestamp of last modification and directory/file name
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
7. What does the following block do?:
Show answer
These system calls are reading the file `/my/file` and 5 is the file descriptor number.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
8. You would like to copy a file to a remote Linux host. How would you do?
Show answer
There are multiple ways to transfer files between hosts. Personal opinion: use `rsync`Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
9. What each of the following matches
Show answer
* The ? matches any single character* The * matches zero or more characters
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
10. How to create your own environment variables?
Show answer
`X=2` for example. But this will persist to new shells. To have it in new shells as well, use `export X=2`Remember: `export VAR=val` for child processes. Without export = current shell only.
Gotcha: .bashrc=interactive shells, .bash_profile=login shells. Source of confusion.
11. How could you modify a text file without invoking a text editor?
Show answer
For example:```bash\n# cat >filename ... - overwrite file\n# cat >>filename ... - append to file\ncat > filename << __EOF__\ndata\n__EOF__\n```
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
12. What exactly does the command alias x=y do?
Show answer
alias x=y creates a shell shortcut where typing 'x' expands to 'y'.Behavior:
- When you type 'x', shell replaces it with 'y'
- Only works in interactive shells
- Doesn't work in scripts (by default)
Examples:
- alias ll='ls -la'
- alias grep='grep --color=auto'
- alias k='kubectl'
Properties:
- Aliases don't take arguments in the middle
- Checked before command lookup
- Can be overridden with \x or command x
Persistence:
- Add to ~/.bashrc or ~/.bash_aliases
- Source file or restart shell
Management:
- alias - List all aliases
- alias x - Show specific alias
- unalias x - Remove alias
13. How cd - works? How does it knows the previous location?
Show answer
The shell stores the previous directory in the `$OLDPWD` environment variable. `cd -` is shorthand for `cd $OLDPWD` and prints the path it switches to.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
14. How can you send an HTTP request from your shell?
Show answer
Use `nc` (netcat) to send raw HTTP requests: `echo -e 'GET / HTTP/1.1\rHost: example.com\r
\r
' | nc example.com 80`. More commonly, use `curl` for HTTP requests: `curl -v https://example.com`. Also available: `wget` for downloads, `httpie` (http command) for a user-friendly CLI. Gotcha: `nc` requires manual HTTP formatting including carriage returns.
15. Demonstrate Linux output redirection
Show answer
`ls > ls_output.txt` redirects stdout to a file, overwriting its contents. Key operators: `>` overwrites, `>>` appends, `2>` redirects stderr, `&>` redirects both stdout and stderr.Example: `find / -name '*.conf' 2>/dev/null` suppresses permission errors. Mnemonic: one arrow overwrites, two arrows append.
16. How would you split a 50 lines file into 2 files of 25 lines each?
Show answer
You can use the `split` command this way: `split -l 25 some_file`Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
17. What defines a "senior" Linux engineer?
Show answer
Not years of experience - demonstrated capabilities:**Failure prediction**:
* Sees problems before they happen
* Understands failure modes
* Designs for resilience
**Blast radius control**:
* Knows what could break from any change
* Tests changes incrementally
* Has rollback plans ready
**Knowing when NOT to act**:
* Resists urge to "fix" working systems
* Asks questions before changing
* Documents understanding before touching
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
18. Explain what each of the following commands does:
Show answer
`useradd` - Command for creating new users`usermod` - Modify the users setting
`whoami` - Outputs, the username that we are currently logged in
`id` - Prints the
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
19. True or False? Directories always have by minimum 2 links
Show answer
True. Every directory has at least 2 hard links: its entry in the parent directory, and the `.` entry inside itself. Each subdirectory adds another link via its `..` entry.Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
20. Is there a way to redirect output to a file and have it display on stdout?
Show answer
The command you want is named tee:`foo | tee output.file`
For example, if you only care about stdout:
`ls -a | tee output.file`
If you want to include stderr, do:
`program [arguments...] 2>&1 | tee outfile`
`2>&1` redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the tee command.
Furthermore, if you want to append to the log file, use `tee -a` as:
`program [arguments...] 2>&1 | tee -a outfile`
21. Name 5 commands which are two letters long
Show answer
Common two-letter commands: ls (list), wc (word count), dd (disk dump), df (disk free), du (disk usage), ps (processes), ip (network config), cp (copy), cd (change directory), mv (move), rm (remove), ln (link). These short names follow Unix philosophy of brevity β frequently used commands get the shortest names.22. How to count the number of lines in a file? What about words?
Show answer
For these we can use `wc` command.1. To count the number of lines in file
```wc -l```
2. To count the number of words in file
```wc -w```
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
23. What ways are there for creating a new empty file?
Show answer
* touch new_file* echo "" > new_file
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
24. Some of the commands in the previous question can be run with the -r/-R flag. What does it do? Give an example to when you would use it
Show answer
The -r (or -R in some commands) flag allows the user to run a certain command recursively. For example, listing all the files under the following tree is possible when done recursively (`ls -R`):/dir1/
dir2/
file1
file2
dir3/
file3
To list all the files, one can run `ls -R /dir1`
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
25. How to follow file's content as it being appended without opening the file every time?
Show answer
tail -fRemember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
26. How to look for a package that provides the command /usr/bin/git? (the package isn't necessarily installed)
Show answer
`dnf provides /usr/bin/git` (RHEL/Fedora) or `apt-file search /usr/bin/git` (Debian/Ubuntu) finds which package provides a specific file, even if the package is not installed. On RHEL: install `yum-utils` for `repoquery --whatprovides`. This is essential when you encounter a 'command not found' error and need to install the right package.27. Do you have experience with packaging (building packages)?
Show answer
Building packages varies by distribution:RPM (RHEL, Fedora, CentOS):
- rpmbuild with .spec file
- Defines build steps, dependencies, files
- Result: .rpm package
DEB (Debian, Ubuntu):
- dpkg-buildpackage
- debian/ directory with control files
- Result: .deb package
Steps typically include:
1. Prepare source
2. Configure build
3. Compile
4. Install to staging directory
5. Package with metadata
Tools:
- Mock/Koji: RPM build environments
- pbuilder/sbuild: DEB build environments
- fpm: Cross-format packaging
- checkinstall: Quick packaging from make install
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
28. How to check if running as root in a bash script? What should you watch out for?
Show answer
In a bash script, you have several ways to check if the running user is root.As a warning, do not check if a user is root by using the root username. Nothing guarantees that the user with ID 0 is called root. It's a very strong convention that is broadly followed but anybody could rename the superuser another name.
I think the best way when using bash is to use `$EUID` because `$UID` could be changed and not reflect the real user running the script.
```bash\nif (( $EUID != 0 )); then\n echo "Please run as root"\n exit\nfi\n```
29. Is there an easy way to search inside 1000s of files in a complex directory structure to find files which contain a specific string?
Show answer
For example use `fgrep`:```bash\nfgrep * -R "string"\n```
or:
```bash\ngrep -insr "pattern" *\n```
- `-i` ignore case distinctions in both the **PATTERN** and the input files
- `-n` prefix each line of output with the 1-based line number within its input file
- `-s` suppress error messages about nonexistent or unreadable files.
- `-r` read all files under each directory, recursively.
Remember: which=PATH, whereis=binary+man+src, type=alias/builtin/file. type is best.
30. Explain what will ls [0-5] match
Show answer
ls [0-5] matches files whose name is exactly ONE character in the range 0-5.It will match files named:
- "0", "1", "2", "3", "4", "5"
It will NOT match:
- "6", "7", "8", "9" (outside range)
- "01" (two characters)
- "file1" (multiple characters)
The [0-5] is a character class range - matches one digit from 0 to 5.
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
31. How to make high availability of web application?
Show answer
Key requirements for managing user access at scale:1. **Authentication**: Centralized identity (LDAP/AD/SSO). MFA for privileged access
2. **Authorization**: Role-based access control (RBAC). Principle of least privilege
3. **Auditing**: Log all access and changes. Regular access reviews
4. **Provisioning**: Automated onboarding/offboarding tied to HR systems
5. **Password policy**: Minimum complexity, rotation, no shared accounts
6. **Privileged access**: Separate admin accounts, just-in-time access, session recording
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
32. A project manager needs a new SQL Server. What do you ask her/his?
Show answer
I want the DBA to ask questions like:- How big will the database be? (whether we can add the database to an existing server)
- How critical is the database? (about clustering, disaster recovery, high availability)
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
33. Explain what will ls [XYZ] match
Show answer
ls [XYZ] matches files whose name is exactly ONE character that is either X, Y, or Z.It will match:
- A file named "X"
- A file named "Y"
- A file named "Z"
It will NOT match:
- "XYZ" (three characters)
- "xy" (lowercase)
- "X1" (two characters)
The brackets define a character class - one character from the set.
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
34. How to exit without saving shell history?
Show answer
`kill -9 $$` kills the current shell process immediately (SIGKILL), preventing history from being saved. Alternatively: `unset HISTFILE && exit` clears the history file variable before exiting gracefully. Also: `history -c && history -w && exit` clears the in-memory history and writes an empty file.Gotcha: `kill -9 $$` may leave child processes orphaned.
35. How do you create a new resource in Kubernetes?
Show answer
* touch new_file.txt* cat > new_file [enter] submit text; ctrl + d to exit insert mode
* truncate -s
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
36. RPM: Explain the .spec format. What should and can it contain?
Show answer
The .spec file defines how to build an RPM package.Main sections:
- Name, Version, Release: Package identity
- Summary, License, URL: Metadata
- Source0: Source tarball location
- BuildRequires: Build dependencies
- Requires: Runtime dependencies
Build sections:
- %prep: Unpack and patch source
- %build: Configure and compile
- %install: Install to buildroot
- %files: List packaged files
- %changelog: Version history
Example:
Name: myapp
Version: 1.0
Release: 1%{?dist}
%build
./configure && make
%install
make install DESTDIR=%{buildroot}
%files
/usr/bin/myapp
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
37. Demonstrate Linux stderr to stdout redirection
Show answer
`yippiekaiyay &> file` redirects both stdout and stderr to the same file. Equivalent long form: `yippiekaiyay > file 2>&1`. Key operators: `>` stdout, `2>` stderr, `&>` both, `>>` append.Gotcha: order matters with the long form β `2>&1 > file` does NOT capture stderr to the file because redirection is processed left to right.
38. List three ways to print all the files in the current directory
Show answer
* ls* find .
* echo *
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
39. What types of web servers are you familiar with?
Show answer
Common web servers: Nginx (event-driven, excels at reverse proxy and static content) and Apache httpd (process/thread-based, highly extensible with modules). Others: Caddy (automatic HTTPS), Lighttpd (lightweight), and Traefik (cloud-native reverse proxy with auto-discovery). Nginx is the most popular for modern deployments due to lower memory footprint and built-in load balancing.40. What each of the following commands does?
Show answer
* cd / -> change to the root directory* cd ~ -> change to your home directory
* cd -> change to your home directory
* cd .. -> change to the directory above your current i.e parent directory
* cd . -> change to the directory you currently in
* cd - -> change to the last visited path
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
41. Demonstrate one way to encode and decode data in Linux
Show answer
Encode: `echo -n "some password" | base64`Decode: `echo -n "allE19remO91" | base64`
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
42. What do > and < do in terms of input and output for programs?
Show answer
They take in input (<) and output for a given file (>) using stdin and stdout.`myProgram < input.txt > executionOutput.txt`
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
43. How to find out the dynamic libraries executables loads when run?
Show answer
`ldd /bin/ls` lists the shared libraries (dynamic dependencies) that an executable loads at runtime. Example output shows libpthread.so, libc.so, and the dynamic linker (ld-linux).Gotcha: never run `ldd` on untrusted binaries β it may execute them. Use `objdump -p
44. How to create a file of a certain size?
Show answer
There are a couple of ways to do that:* dd if=/dev/urandom of=new_file.txt bs=2MB count=1
* truncate -s 2M new_file.txt
* fallocate -l 2097152 new_file.txt
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
45. What is the main purpose of the intermediate certification authorities?
Show answer
An intermediate CA sits between the root CA and end-entity certificates in the trust chain.Purpose:
- **Protects root CA**: Root stays offline/air-gapped. Intermediate handles day-to-day signing
- **Limits blast radius**: If compromised, only the intermediate is revoked, not the entire PKI
- **Organizational delegation**: Different intermediates for different departments or purposes
Trust chain: Root CA -> Intermediate CA -> Server/Client certificate. Servers must send the intermediate cert along with their own cert so clients can verify the full chain.
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
46. Demonstrate Linux stderr output redirection
Show answer
`yippiekaiyay 2> error.txt` redirects stderr (file descriptor2) to error.txt while stdout still goes to the terminal. Useful for capturing error messages separately from normal output.
Example: `find / -name '*.conf' 2> /dev/null` suppresses 'Permission denied' errors. Append with `2>>` instead of `2>` to avoid overwriting existing error logs.
47. What is the preferred bash shebang and why? What is the difference between executing a file using ./script or bash script?
Show answer
You should use `#!/usr/bin/env bash` for portability: different \*nixes put bash in different places, and using `/usr/bin/env` is a workaround to run the first bash found on the `PATH`.Running `./script` does exactly that, and requires execute permission on the file, but is agnostic to what type of a program it is. It might be a **bash script**, an **sh script**, or a **Perl**, **Python**, **awk**, or **expect script**, or an actual **binary executable**. Running `bash script` would force it to be run under `sh`, instead of anything else.
π΄ Hard (10)¶
1. The program returns the error of the missing library. How to provide dynamically linkable libraries?
Show answer
Environment variable `LD_LIBRARY_PATH` is a colon-separated set of directories where libraries should be searched for first, before the standard set of directories; this is useful when debugging a new library or using a nonstandard library for special purposes.The best way to use `LD_LIBRARY_PATH` is to set it on the command line or script immediately before executing the program. This way the new `LD_LIBRARY_PATH` isolated from the rest of your system.
Example of use:
```bash\nexport LD_LIBRARY_PATH="/list/of/library/paths:/another/path" ./program\n```
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
2. The Junior dev accidentally destroyed production database. How can you prevent such situations?
Show answer
Prevent production disasters with layered safeguards:1. **Access control**: Restrict prod DB access to senior engineers. Use separate credentials per environment
2. **Backups & tested restores**: Regular automated backups with periodic restore tests. Snapshots before changes
3. **Environment isolation**: Separate dev/test/prod with different auth credentials. Never develop against prod
4. **Disaster recovery plan**: Documented DR procedures with a backup datacenter or failover region
5. **Replication with delay**: Slightly delayed replicas give a window to catch destructive mistakes
6. **Post-mortems**: Document incidents to prevent recurrence. Focus on systemic fixes, not blame
3. How to add new user without using useradd/adduser commands?
Show answer
1. Add an entry of user details in `/etc/passwd` with `vipw`:```bash\n# username:password:UID:GID:Comments:Home_Directory:Login Shell\nuser:x:501:501:test user:/home/user:/bin/bash\n```
> Be careful with the syntax. Do not edit directly with an editor. `vipw` locks the file, so that other commands won't try to update it at the same time.
2. You will have to create a group with same name in `/etc/group` with `vigr` (similar tool for `vipw`):
```bash\nuser:x:501:\n```
3. Assign a password to the user:
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
4. How to read a file line by line and assigning the value to a variable?
Show answer
For example:```bash\nwhile IFS='' read -r line || [[ -n "$line" ]] ; do\n echo "Text read from file: $line"\ndone < "/path/to/filename"\n```
Explanation:
- `IFS=''` (or `IFS=`) prevents leading/trailing whitespace from being trimmed.
- `-r` prevents backslash escapes from being interpreted.
- `|| [[ -n $line ]]` prevents the last line from being ignored if it doesn't end with a `
` (since read returns a non-zero exit code when it encounters EOF).
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
5. How do you run command every time a file is modified?
Show answer
For example:```bash\nwhile inotifywait -e close_write filename ; do\n\n echo "changed" >> /var/log/changed\n\ndone\n```
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
6. What is the easiest, safest and most portable way to remove -rf directory entry?
Show answer
They're effective but not optimally portable:- `rm -- -fr`
- `perl -le 'unlink("-fr");'`
People who go on about shell command line quoting and character escaping are almost as dangerous as those who simply don't even recognize why a file name like that poses any problem at all.
The most portable solution:
```bash\nrm ./-fr\n```
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
7. How to remove all files except some from a directory?
Show answer
Solution 1 - with `extglob`:```bash\nshopt -s extglob\nrm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt)\n```
Solution 2 - with `find`:
```bash\nfind . -type f -not -name '*txt' -print0 | xargs -0 rm --\n```
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.
8. Why do we need mktemp command? Present an example of use.
Show answer
`mktemp` randomizes the name. It is very important from the security point of view.Just imagine that you do something like:
```bash\necho "random_string" > /tmp/temp-file\n```
in your root-running script. And someone (who has read your script) does
```bash\nln -s /etc/passwd /tmp/temp-file\n```
The `mktemp` command could help you in this situation:
```bash\nTEMP=$(mktemp /tmp/temp-file.XXXXXXXX)\necho "random_string" > ${TEMP}\n```
Now this `ln /etc/passwd` attack will not work.
Remember: Man sections: 1=commands, 5=file formats, 8=admin. `man 5 passwd` = file format.
9. How to redirect stderr and stdout to different files in the same line?
Show answer
Just add them in one line `command 2>> error 1>> output`.However, note that `>>` is for appending if the file already has data. Whereas, `>` will overwrite any existing data in the file.
So, `command 2> error 1> output` if you do not want to append.
Just for completion's sake, you can write `1>` as just `>` since the default file descriptor is the output. so `1>` and `>` is the same thing.
So, `command 2> error 1> output` becomes, `command 2> error > output`.
10. How to check if a string contains a substring in Bash?
Show answer
You can use `*` (wildcards) outside a case statement, too, if you use double brackets:```bash\nstring='some text'\nif [[ $string = *"My long"* ]] ; then\n true\nfi\n```
Remember: Unix philosophy: one thing well, compose with pipes. `man cmd` is your friend.
Gotcha: Test destructive commands with echo or --dry-run first.