Skip to content

Linux General

← Back to all decks

164 cards β€” 🟒 67 easy | 🟑 85 medium | πŸ”΄ 12 hard

🟒 Easy (67)

1. What command shows the current directory path?

Show answer pwd (Print Working Directory).

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
bash --login -x
```

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
echo $PATH
```

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.

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.

5. How do you find a text string in files on Linux?

Show answer Using the grep command (e.g., grep "search_term" filename).

6. What is your favorite shell and why?

Show answer **BASH** is my favorite. It’s really a preferential kind of thing, where I love the syntax and it just "clicks" for me. The input/output redirection syntax (`>>`, `<< 2>&1`, `2>`, `1>`, etc) is similar to C++ which makes it easier for me to recognize.

I also like the **ZSH** shell, because is much more customizable than **BASH**. It has the Oh-My-Zsh framework, powerful context based tab completion, pattern matching/globbing on steroids, loadable modules and more.

7. What is DNF and what is it used for in Linux package management?

Show answer From the [repo](https://github.com/rpm-software-management/dnf):

"Dandified YUM (DNF) is the next upcoming major version of YUM. It does package management using RPM, libsolv and hawkey libraries."

Official [docs](https://dnf.readthedocs.io/en/latest/)

8. 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.

9. 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`.

10. 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.

11. You have to find all files larger than 20MB. How you do it?

Show answer ```bash
find / -type f -size +20M
```

12. What does rm -rf do and why is it dangerous?

Show answer Recursively and forcibly removes a directory and its contents.

13. 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 \, $, `, ", !

14. What is the difference between man and info?

Show answer A good answer can be found [here](https://askubuntu.com/questions/9325/what-is-the-difference-between-man-and-info-documentation)

15. 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.

16. 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

17. What is the $ sign in a shell prompt usually indicative of?

Show answer A standard user session.

18. What is a TTY device?

Show answer TTY (TeleTYpewriter) is a terminal device for user I/O.

Types:
- /dev/tty[1-6]: Virtual consoles (Ctrl+Alt+F1-F6)
- /dev/pts/N: Pseudo-terminals (SSH, terminal emulators)
- /dev/ttyS*: Serial ports
- /dev/ttyUSB*: USB serial devices

TTY subsystem provides:
- Line editing (backspace, etc.)
- Signal generation (Ctrl+C)
- Job control (foreground/background)
- Terminal modes (raw, cooked)

Commands:
- tty - Print current terminal
- who - Shows user terminals
- stty - Configure terminal settings
- write - Send message to terminal

Check terminal:
- tty command or echo $TTY
- /dev/pts/0 typical for SSH/terminal

19. What does the ls command do in Linux?

Show answer It lists directory contents (files and folders) in the current working directory.

20. 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.

21. How to find files that have been modified on your system in the past 60 minutes?

Show answer ```bash
find / -mmin -60 -type f
```

22. 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).

23. What is an exit code? What exit codes are you familiar with?

Show answer An exit code (or return code) represents the code returned by a child process to its
parent process.

0 is an exit code which represents success while anything higher than 1 represents error.
Each number has different meaning, based on how the application was developed.

I consider this as a good blog post to read more about it: https://shapeshed.com/unix-exit-codes

24. What is a CLI? Tell me about your favorite CLI tools, tips, and hacks.

Show answer **CLI** (Command Line Interface) is a text-based interface for interacting with the OS by typing commands.

Key concepts:
- Shell (bash, zsh) interprets and executes commands
- Commands follow the pattern: `command [options] [arguments]`
- Supports piping (`|`), redirection (`>`, `<`), and scripting
- More powerful than GUI for automation, remote access (SSH), and batch operations

Essential for DevOps: nearly all server administration, CI/CD, and infrastructure management happens via CLI.

25. 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.

26. What is special about the /tmp directory when compared to other directories?

Show answer `/tmp` folder is cleaned automatically, usually upon reboot.

27. 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

28. How can I sync two local directories?

Show answer To sync the contents of **dir1** to **dir2** on the same system, type:

```bash
rsync -av --progress --delete dir1/ dir2
```

- `-a`, `--archive` - archive mode
- `--delete` - delete extraneous files from dest dirs
- `-v`, `--verbose` - verbose mode (increase verbosity)
- `--progress` - show progress during transfer

29. 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.

30. How would you check what is the size of a certain directory?

Show answer `du -sh ` β€” `-s` summarizes (total only), `-h` makes it human-readable. Without `-s`, it lists every subdirectory. `du -sh *` shows sizes of all items in current dir.

31. 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)

32. 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.

33. How do you create a shortcut for a complex command in Bash?

Show answer By adding an alias to the .bashrc file.

34. 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.

35. What does cd ~ accomplish?

Show answer It returns the user to their home directory.

36. What is the # sign in a shell prompt usually indicative of?

Show answer A superuser (root) session.

37. Why are there different sections in man? What is the difference?

Show answer Man pages are organized into numbered sections by topic.

Sections:
1. User commands (ls, cp, cat)
2. System calls (open, read, fork)
3. Library functions (printf, malloc)
4. Special files (/dev devices)
5. File formats (/etc/passwd format)
6. Games
7. Miscellaneous (conventions, standards)
8. System admin commands (mount, systemctl)

Why sections exist:
- Same name in different contexts
- Example: printf(1) command vs printf(3) C function
- Example: passwd(1) command vs passwd(5) file format

Access specific section:
- man 1 printf - Command
- man 3 printf - C function
- man 5 passwd - File format

Find all:
- man -k keyword - Search descriptions
- man -f command - List all sections

38. 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).

39. 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.

40. 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

41. 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.

42. What is stored in each of the following logs: /var/log/messages, /var/log/syslog, /var/log/auth.log?

Show answer These are key system log files:

/var/log/messages (RHEL/CentOS):
- General system messages
- Kernel messages
- Service start/stop
- Hardware events

/var/log/syslog (Debian/Ubuntu):
- Similar to messages
- General system log
- Most daemon output

/var/log/auth.log (or secure):
- Authentication events
- SSH logins/failures
- sudo usage
- PAM messages

With systemd, also use:
- journalctl - All logs
- journalctl -u service - Specific service
- journalctl -p err - By priority

43. 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.

44. 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.

45. 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

46. 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

47. 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

48. What does kill command do?

Show answer In Unix and Unix-like operating systems, `kill` is a command used to send a signal to a process. By default, the message sent is the termination signal, which requests that the process exit. But `kill` is something of a misnomer; the signal sent may have nothing to do with process killing.

49. How do you get a list of logged-in users?

Show answer For a summary of logged-in users, including each login of a username, the terminal users are attached to, the date/time they logged in, and possibly the computer from which they are making the connection, enter:

```bash
# It uses /var/run/utmp and /var/log/wtmp files to get the details.
who
```

For extensive information, including username, terminal, IP number of the source computer, the time the login began, any idle time, process CPU cycles, job CPU cycles, and the currently running command, enter:

```bash
# It uses /var/run/utmp, and their processes /proc.
w
```

Also important for displays a list of last logged in users, enter:

```bash
# It uses /var/log/wtmp.
last
```

50. What do the fields in ls -al output mean?

Show answer In the order of output:

```bash
-rwxrw-r-- 1 root root 2048 Jan 13 07:11 db.dump
```

- 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

51. How is a user’s default group determined? How would you change it?

Show answer ```bash
useradd -m -g initial_group username
```

`-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**.

52. You run dig codingshell.com and get the following result:

Show answer This is the TTL. When you lookup for an address using a domain/host name, your OS is performing DNS resolution by contacting DNS name servers to get the IP address of the host/domain you are looking for.
When you get a reply, this reply in cached in your OS for a certain period of time. This is period of time is also known as TTL and this is the meaning of 3515 number - it will be cached for 3515 seconds before removed from the cache and during that period of time, you'll get the value from the cache instead of asking DNS name servers for the address again.

53. 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

54. What is grep command? How to match multiple strings in the same line?

Show answer The `grep` utilities are a family of Unix tools, including `egrep` and `fgrep`.

`grep` searches file patterns. If you are looking for a specific pattern in the output of another command, `grep` highlights the relevant lines. Use this grep command for searching log files, specific processes, and more.

For match multiple strings:

```bash
grep -E "string1|string2" filename
```

or

```bash
grep -e "string1" -e "string2" filename
```

55. How can you check what is the path of a certain command?

Show answer * whereis
* which

56. What does the man command provide?

Show answer The manual page for a specific command.

57. What is the .bashrc file?

Show answer A script executed when a new interactive shell starts.

58. 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).

59. What is CUPS and how does it handle printing in Linux?

Show answer CUPS (Common Unix Printing System) manages printing on Linux/Unix.

Features:
- Print queue management
- Driver support (PPD files)
- Network printing (IPP protocol)
- Web interface (localhost:631)

Components:
- cupsd: Main daemon
- /etc/cups/: Configuration
- /var/spool/cups/: Print queues

Commands:
- lpstat -p: List printers
- lp -d printer file: Print file
- lpq: Show queue
- lprm job_id: Cancel job

Web admin: http://localhost:631
- Add printers
- Manage queues
- View logs

60. 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.

61. 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`.

62. 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
cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install
```

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
cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install
```

63. Explain the file content commands along with the description.

Show answer - `head`: to check the starting of a file.
- `tail`: to check the ending of the file. It is the reverse of head command.
- `cat`: used to view, create, concatenate the files.
- `more`: used to display the text in the terminal window in pager form.
- `less`: used to view the text in the backward direction and also provides single line movement.

64. 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`)

65. What does tail -f do?

Show answer Monitors file changes in real-time.

66. Tell me about your Linux experience.

Show answer I've managed large-scale Linux environments for over 15 years β€” from RHEL 4–9, CentOS, Ubuntu, and CoreOS. Most of my work has been operational: patching, performance tuning, troubleshooting services, storage, networking, and writing automation around daily tasks. I'm very strong with systemd, networking services, SELinux, and debugging production issues under pressure.

67. Explain environment variables. How do you list all of them?

Show answer Environment variables are name-value pairs passed to processes.

Purpose:
- Configure program behavior
- Pass information to child processes
- System configuration (PATH, HOME, etc.)

Common variables:
- PATH: Command search paths
- HOME: User's home directory
- USER: Current username
- SHELL: Default shell
- LANG: Language/locale
- PWD: Current directory

List them:
- env - All environment variables
- printenv - Same as env
- printenv VAR - Specific variable
- echo $VAR - Print specific value
- export - Show exported variables

Set variables:
- export VAR=value (for child processes)
- VAR=value (shell only, not inherited)

Persistence: Add to ~/.bashrc or ~/.profile

🟑 Medium (85)

1. How to generate a random string of 7 characters?

Show answer `mkpasswd -l 7`

2. How to rename the name of a file or a directory?

Show answer Using the `mv` command.

3. Explain what each of the following commands does and give an example on how to use it:

Show answer * touch - update file's timestamp. More commonly used for creating files
* ls - listing files and directories
* rm - remove files and directories
* cat - create, view and concatenate files
* cp - copy files and directories
* mkdir - create directories
* pwd - print current working directory (= at what path the user currently located)
* cd - change directory

4. 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**.

5. What do we grep for in each of the following commands?:

Show answer 1. An IP address
2. The word "error" or "failure"
3. Lines which end with a number

6. What the following commands do?

Show answer * chmod - changes access permissions to files system objects
* chown - changes the owner of file system files and directories
* chgrp - changes the group associated with a file system object

7. How packages installation/removal is performed on the distribution you are using?

Show answer The answer depends on the distribution being used.

In Fedora/CentOS/RHEL/Rocky it can be done with `rpm` or `dnf` commands.
In Ubuntu it can be done with the `apt` command.

8. Create a file with 100 lines with random values.

Show answer For example:

```bash
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 100 > /path/to/file
```

9. What happens when you execute ls -l?

Show answer * Shell reads the input using getline() which reads the input file stream and stores into a buffer as a string
* The buffer is broken down into tokens and stored in an array this way: {"ls", "-l", "NULL"}
* Shell checks if an expansion is required (in case of ls *.c)

* Once the program in memory, its execution starts. First by calling readdir()

Notes:

* getline() originates in GNU C library and used to read lines from input stream and stores those lines in the buffer

10. 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

11. Specify which command would you use (and how) for each of the following scenarios

Show answer - `rm -rf dir`
- `cat or less`
- `chmod 777 /tmp/x`
- `cd ~`
- `sed -i s/good/great/g /tmp/y`

12. 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

13. What does the following block do?:

Show answer These system calls are reading the file `/my/file` and 5 is the file descriptor number.

14. 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`

15. How do you find all processes owned by a specific user in Linux?

Show answer If you mention at any point ps command with arguments, be familiar with what these arguments does exactly.

16. You have the task of sync the testing and production environments. What steps will you take?

Show answer Steps to sync testing and production environments:

1. **Snapshot production**: Create DB dump and disk/VM snapshots
2. **Restore to test**: Import snapshots into testing environment
3. **Sanitize data**: Remove/mask sensitive data (PII, credentials)
4. **Sync packages**: Match OS and application versions
5. **Update configs**: Adjust environment-specific settings (hostnames, endpoints, credentials)
6. **Verify**: Run smoke tests to confirm parity

Key principle: Only production is production. Use infrastructure-as-code and deploy scripts to minimize drift.

17. Can you give a particular example when is indicated to use nobody account? Tell me the differences running httpd service as a nobody and www-data accounts.

Show answer In Unix, `nobody` is a user account that owns no files and has no special privileges. It is used to run daemons that don't need filesystem access (e.g., memcached).

**nobody vs www-data for httpd:**
- `nobody`: Shared across services. If one service is compromised, attacker gains access to all nobody-owned processes
- `www-data`: Application-specific user. Isolates Apache from other services. Preferred for web servers

Best practice: Use per-service accounts (www-data, postgres, etc.) rather than the shared nobody account. This limits blast radius if a service is compromised.

18. Describe shortly what happens when you execute a command in the shell

Show answer The shell figures out, using the PATH variable, where the executable of the command resides in the filesystem. It then calls fork() to create a new child process for running the command. Once the fork was executed successfully, it calls a variant of exec() to execute the command and finally, waits the command to finish using wait(). When the child completes, the shell returns from wait() and prints out the prompt again.

19. What each of the following matches

Show answer * The ? matches any single character
* The * matches zero or more characters

20. 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`

21. How could you modify a text file without invoking a text editor?

Show answer For example:

```bash
# cat >filename ... - overwrite file
# cat >>filename ... - append to file
cat > filename << __EOF__
data
__EOF__
```

22. Find all the files which end with '.yml' and replace the number 1 in 2 in each file

Show answer find /some_dir -iname \*.yml -print0 | xargs -0 -r sed -i "s/1/2/g"

23. 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

24. 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.

25. How can you send an HTTP request from your shell?

Show answer Using nc is one way

26. Running the command df you get "command not found". What could be wrong and how to fix it?

Show answer Most likely the default $PATH was modified or overridden, so `/bin/` (where df lives) is missing.

Fix:
1. Manually reset PATH: `PATH=/bin:/sbin:/usr/bin:/usr/sbin`
2. Check what broke it: review `~/.bashrc`, `~/.bash_profile`, `/etc/profile`
3. Fix the offending file and source it: `source ~/.bashrc`

To schedule periodic tasks, use `cron`:
`crontab -e` then add entries like: `*/30 * * * * bash myscript.sh`
Format: ` `. On systemd distros, consider systemd timers as an alternative.

27. What the awk command does? Have you used it? What for?

Show answer From Wikipedia: "AWK is domain-specific language designed for text processing and typically used as a data extraction and reporting tool"

28. Demonstrate Linux output redirection

Show answer `ls > ls_output.txt`

29. 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`

30. What does it mean when the effective user is root, but the real user ID is still your name?

Show answer The **real user ID** is who you really are (the user who owns the process), and the **effective user ID** is what the operating system looks at to make a decision whether or not you are allowed to do something (most of the time, there are some exceptions).

When you log in, the login shell sets both the **real and effective user ID** to the same value (your **real user ID**) as supplied by the password file.

31. How to check which commands you executed in the past?

Show answer history command or .bash_history file
* also can use up arrow key to access or to show the recent commands you type

32. How to print every line that is longer than 79 characters?

Show answer `awk 'length($0) > 79' file`

33. 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

34. You try to create a file but it fails. Name at least three different reason as to why it could happen

Show answer * No more disk space
* No more inodes
* No permissions

35. 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

36. 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.

37. 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`

38. Developer added cron job which generate massive log files. How do you prevent them from getting so big?

Show answer Using `logrotate` is the usual way of dealing with logfiles. But instead of adding content to `/etc/logrotate.conf` you should add your own job to `/etc/logrotate.d/`, otherwise you would have to look at more diffs of configuration files during release upgrades.

If it's actively being written to you don't really have much you can do by way of truncate. Your only options are to truncate the file:

```bash
: >/var/log/massive-logfile
```

It's very helpful, because it's truncate the file without disrupting the processes.

39. What kind of information one can find in /proc?

Show answer It contains useful information about the processes that are currently running, it is regarded as control and information center for kernel.

40. How to generate a random string?

Show answer One way is to run the following: `cat /proc/sys/kernel/random/uuid`

41. Name 5 commands which are two letters long

Show answer ls, wc, dd, df, du, ps, ip, cp, cd ...

42. 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```

43. What ways are there for creating a new empty file?

Show answer * touch new_file
* echo "" > new_file

44. 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`

45. How to follow file's content as it being appended without opening the file every time?

Show answer tail -f

46. What is the difference between a service failure and a dependency failure?

Show answer Service failure is the unit itself exiting non-zero or crashing. The process ran but failed.

Dependency failure means a required unit (specified via `Requires=` or `BindsTo=`) failed earlier, so systemd never attempted to start the dependent service.

To diagnose:
```bash
systemctl status myservice
journalctl -u myservice
systemctl list-dependencies myservice --reverse
```

Dependency failures show "dependency failed" in status; service failures show the actual exit code.

47. 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

48. 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

49. 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
if (( $EUID != 0 )); then
echo "Please run as root"
exit
fi
```

50. How to print the 4th column in a file?

Show answer `awk '{print $4}' file`

51. 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
fgrep * -R "string"
```

or:

```bash
grep -insr "pattern" *
```

- `-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.

52. How to reload PostgreSQL after configuration changes?

Show answer Solution 1:

```bash
systemctl reload postgresql
```

Solution 2:

```
su - postgres
/usr/bin/pg_ctl reload
```

Solution 3:

```
SELECT pg_reload_conf();
```

53. What a double dash (--) mean?

Show answer It's used in commands to mark the end of commands options. One common example is when used with git to discard local changes: `git checkout -- some_file`

54. You executed a script and while still running, it got accidentally removed. Is it possible to restore the script while it's still running?

Show answer It is possible to restore a script while it's still running if it has been accidentally removed. The running script process still has the code in memory. You can use the /proc filesystem to retrieve the content of the running script.
1.Find the Process ID by running
```
ps aux | grep yourscriptname.sh
```
Replace yourscriptname.sh with your script name.
2.Once you have the PID, you can access the script's memory through the /proc filesystem.

55. 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.

56. You define x=2 in /etc/bashrc and x=6 in ~/.bashrc. You then log in. What is the value of x?

Show answer x=6 (user's .bashrc overrides system bashrc)

Order of execution (login shell):
1. /etc/profile
2. ~/.bash_profile (or ~/.bash_login or ~/.profile)
- Often sources ~/.bashrc
3. /etc/bashrc (typically sourced by .bashrc)
4. ~/.bashrc

For login shells:
- System files first, user files after
- Later definitions override earlier ones
- x=2 set in /etc/bashrc
- x=6 set in ~/.bashrc (wins)

Important notes:
- Non-login shells may differ
- Depends on how files source each other
- .bashrc usually sources /etc/bashrc first

Result: x=6 (user config takes precedence)

57. Using sed, extract the date from the following line: 201.7.19.90 - - [05/Jun/1985:13:42:99 +0000] "GET /site HTTP/1.1" 200 32421

Show answer `echo $line | sed 's/.*\[//g;s/].*//g;s/:.*//g'`

58. Explain piping. How do you perform piping?

Show answer Using a pipe in Linux, allows you to send the output of one command to the input of another command. For example: `cat /etc/services | wc -l`

59. Present and explain the good ways of using the kill command.

Show answer Speaking of killing processes never use `kill -9/SIGKILL` unless absolutely mandatory. This kill can cause problems because of its brute force.

Always try to use the following simple procedure:

- first, send **SIGTERM** (`kill -15`) signal first which tells the process to shutdown and is generally accepted as the signal to use when shutting down cleanly (but remember that this signal can be ignored).
- next try to send **SIGHUP** (`kill -1`) signal which is commonly used to tell a process to shutdown and restart, this signal can also be caught and ignored by a process.

The far majority of the time, this is all you need - and is much cleaner.

60. True or False? only root can create files in /proc

Show answer False. No one can create file in /proc directly (certain operations can lead to files being created in /proc by the kernel).

61. 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

62. What are hidden files/directories? How to list them?

Show answer These are files directly not displayed after performing a standard ls direct listing. An example of these files are .bashrc which are used to execute some scripts. Some also store configuration about services on your host like .KUBECONFIG. The command used to list them is, `ls -a`

63. 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)

64. 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.

65. Which line numbers will be printed when running grep '\baaa\b' on the following content:

Show answer Lines 1 and 3. The `\b` anchor matches a word boundary, so `\baaa\b` matches 'aaa' only as a whole word β€” not when it appears as a substring inside a longer string like 'aaaa' or 'xaaax'.

66. How to exit without saving shell history?

Show answer ```bash
kill -9 $$
```

or

```bash
unset HISTFILE && exit
```

67. Where are Linux system logs located, and what are the key log files?

Show answer /var/log is the standard log directory. Key files: `/var/log/syslog` or `/var/log/messages` (general system logs), `/var/log/auth.log` or `/var/log/secure` (authentication events), `/var/log/kern.log` (kernel messages), `/var/log/dmesg` (boot messages). On systemd systems, use `journalctl` to query the journal. Log rotation is managed by `logrotate`.

68. 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 new_file.txt

69. 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

70. Demonstrate Linux stderr to stdout redirection

Show answer `yippiekaiyay &> file`

71. How to print the shared libraries required by a certain program?

Show answer Use ldd or other tools:

ldd (List Dynamic Dependencies):
- ldd /bin/ls
- Shows all shared libraries needed
- Security note: Don't run on untrusted binaries

Alternative methods:
- readelf -d binary | grep NEEDED
- objdump -p binary | grep NEEDED

Runtime loaded libraries:
- lsof -p PID | grep '.so' - Currently loaded
- cat /proc/PID/maps - Memory mappings

If library missing:
- ldd shows "not found"
- Fix: Install package or set LD_LIBRARY_PATH

72. Explain Linux I/O redirection

Show answer In Linux, IO redirection is a way of changing the default input/output behavior of a command or program. It allows you to redirect input and output from/to different sources/destinations, such as files, devices, and other commands.

Here are some common examples of IO redirection:
* Redirecting Standard Output (stdout):
`ls > filelist.txt`
* Redirecting Standard Error (stderr):
`ls /some/nonexistent/directory 2> error.txt`
* Appending to a file:
`echo "hello" >> myfile.txt`
* Redirecting Input (stdin):
`sort < unsorted.txt`
* Using Pipes: Pipes ("|"):
`ls | grep "\.txt$"`

73. List three ways to print all the files in the current directory

Show answer * ls
* find .
* echo *

74. What types of web servers are you familiar with?

Show answer Nginx, Apache httpd.

75. 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

76. Demonstrate one way to encode and decode data in Linux

Show answer Encode: `echo -n "some password" | base64`
Decode: `echo -n "allE19remO91" | base64`

77. 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`

78. How to find out the dynamic libraries executables loads when run?

Show answer You can do this with `ldd` command:

```bash
ldd /bin/ls
```

79. 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

80. 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.

81. Fix the following commands:

Show answer ```
sed 's/1/2/g' /tmp/myFile # sed "s/1/2/g" is also fine
find . -iname "*.yaml" -exec sed -i "s/1/2/g" {} \;
```

82. What can be found in /proc/cmdline?

Show answer The command passed to the boot loader to run the kernel

83. Demonstrate Linux stderr output redirection

Show answer `yippiekaiyay 2> ls_output.txt`

84. What does LC_ALL=C before command do? In what cases it will be useful?

Show answer `LC_ALL` is the environment variable that overrides all the other localisation settings. This sets all `LC_` type variables at once to a specified locale.

The main reason to set `LC_ALL=C` before command is that fine to simply get English output (general change the locale used by the command).

On the other hand, also important is to increase the speed of command execution with `LC_ALL=C` e.g. `grep` or `fgrep`. Using the `LC_ALL=C` locale increased our performance and brought command execution time down.

85. 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 (12)

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
export LD_LIBRARY_PATH="/list/of/library/paths:/another/path" ./program
```

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
# username:password:UID:GID:Comments:Home_Directory:Login Shell
user:x:501:501:test user:/home/user:/bin/bash
```

> 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
user:x:501:
```

3. Assign a password to the user:

4. How to prevent dd from freezing your system?

Show answer Try using ionice:

```bash
ionice -c3 dd if=/dev/zero of=file
```

This start the `dd` process with the "idle" IO priority: it only gets disk time when no other process is using disk IO for a certain amount of time.

Of course this can still flood the buffer cache and cause freezes while the system flushes out the cache to disk. There are tunables under `/proc/sys/vm/` to influence this, particularly the `dirty_*` entries.

5. How to read a file line by line and assigning the value to a variable?

Show answer For example:

```bash
while IFS='' read -r line || [[ -n "$line" ]] ; do
echo "Text read from file: $line"
done < "/path/to/filename"
```

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).

6. How do you run command every time a file is modified?

Show answer For example:

```bash
while inotifywait -e close_write filename ; do

echo "changed" >> /var/log/changed

done
```

7. How to log all commands run by root on production servers?

Show answer `auditd` is the correct tool for the job here:

1. Add these 2 lines to `/etc/audit/audit.rules`:

```bash
-a exit,always -F arch=b64 -F euid=0 -S execve
-a exit,always -F arch=b32 -F euid=0 -S execve
```

These will track all commands run by root (euid=0). Why two rules? The execve syscall must be tracked in both 32 and 64 bit code.

2. To get rid of `auid=4294967295` messages in logs, add `audit=1` to the kernel's cmdline (by editing `/etc/default/grub`)

3. Place the line

8. 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
rm ./-fr
```

9. How to remove all files except some from a directory?

Show answer Solution 1 - with `extglob`:

```bash
shopt -s extglob
rm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt)
```

Solution 2 - with `find`:

```bash
find . -type f -not -name '*txt' -print0 | xargs -0 rm --
```

10. 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
echo "random_string" > /tmp/temp-file
```

in your root-running script. And someone (who has read your script) does

```bash
ln -s /etc/passwd /tmp/temp-file
```

The `mktemp` command could help you in this situation:

```bash
TEMP=$(mktemp /tmp/temp-file.XXXXXXXX)
echo "random_string" > ${TEMP}
```

Now this `ln /etc/passwd` attack will not work.

11. 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`.

12. 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
string='some text'
if [[ $string = *"My long"* ]] ; then
true
fi
```