Bash Interview Q&A
1. What is Bash and why is it used?
Bash (Bourne Again SHell) is a Unix shell and command language used for command-line scripting, automating tasks, and system administration.
2. How do you check if a file or directory exists in Bash?
Use the test command or [ ] syntax: `if [ -f filename ]; then ...` for files or `if [ -d directory ]; then ...` for directories.
3. How do you make a Bash script executable?
Use `chmod +x script.sh` to make a script executable.
4. How do you read user input in Bash?
Use the `read` command: `read variable_name`.
5. How do you pass command-line arguments to a Bash script?
Arguments are accessed as `$1`, `$2`, etc., and `$0` is the script name.
6. How do you loop through a list of items in Bash?
Use a for loop: `for item in list; do ...; done` or a while loop with condition.
7. How do you check the exit status of a command?
Use the special variable `$?` which contains the exit code of the last executed command.
8. How do you redirect output and errors in Bash?
Use `>` for stdout, `2>` for stderr, `&>` for both: `command > output.txt 2> error.txt`.
9. How do you find a string in a file?
Use `grep` command: `grep 'search_string' filename`.
10. How do you schedule a script to run automatically?
Use `cron` jobs. Edit crontab with `crontab -e` and define schedule and command.
11. How do you handle command-line arguments in a loop?
Use a while loop with `shift` to iterate: `while [ $# -gt 0 ]; do echo $1; shift; done`.
12. How do you check memory, CPU, and disk usage in Bash?
Use commands like `free`, `top` or `vmstat` for memory/CPU, and `df -h` for disk usage.
13. How do you append text to a file?
Use `>>` operator: `echo 'text' >> file.txt`.
14. How do you handle errors in a Bash script?
Check exit codes with `$?`, use `set -e` to exit on errors, or `trap` to handle signals.
15. How do you extract a substring from a string in Bash?
Use `${variable:position:length}` syntax: `echo ${string:0:5}`.
16. How do you replace text in a file using Bash?
Use `sed`: `sed -i 's/old_text/new_text/g' filename`.
17. How do you create a function in Bash?
Use the syntax: `function_name() { commands; }` and call it by `function_name`.
18. How do you check if a variable is empty or not?
Use: `if [ -z "$VAR" ]; then echo 'Empty'; else echo 'Not empty'; fi`.
19. How do you run a command in the background?
Add `&` at the end of the command: `command &`.
20. How do you loop through files in a directory?
Use: `for file in /path/*; do echo $file; done`.