Linux Fundamentals bash










 

Linux Commands – echo, clear, sleep

🧠 FAANG-Level Interview Q&A with Examples & Explanations


🔹 1. echo – Text Output & Debugging

#

Question

Answer / Example

Explanation

1

What does echo do in shell scripting?

echo "Hello, FAANG"

Prints strings or variables to stdout

2

How to print a variable value?

name="Alice"; echo $name

Outputs value of name

3

How to print without newline?

echo -n "Processing..."

-n omits the trailing newline

4

How do you print special characters like newline?

echo -e "Line1\nLine2"

-e enables interpretation of escape sequences

5

How to append text to a file using echo?

echo "Log entry" >> file.txt

>> appends instead of overwriting

6

What’s the difference between echo $VAR and echo "$VAR"?

Quoting preserves whitespace

Prevents word splitting in variables

7

How to print a command’s output using echo?

echo "Now: $(date)"

Command substitution with $()

8

How do you send echo output to stderr?

echo "error" 1>&2

Useful for logging errors separately

9

How do you print $PATH literally?

echo "\$PATH"

Escape $ with \

10

What are echo's limitations?

Lacks formatting

Use printf when you need precision (e.g., decimal alignment)


🔹 2. clear – Terminal UI Control

#

Question

Answer / Example

Explanation

11

What does the clear command do?

clear

Clears the terminal screen

12

How can clear be used in a script for better UX?

clear; echo "Select option:"

Provides clean interface before input

13

What’s an alternative to clear?

printf "\033c"

ANSI escape code resets terminal

14

Can clear be used in cron jobs?

❌ Not useful

Cron has no terminal

15

How do you use clear with interactive shell menus?

Use before select or read

Keeps prompt clean and readable

16

How to alias clear to cls?

alias cls='clear'

Custom shortcut

17

How is clear helpful in loops?

while true; do clear; date; sleep 1; done

Used to create dynamic terminal dashboards

18

What’s the benefit of using clear in login scripts?

clear; echo "Welcome!"

Clean welcome screen for users

19

How to clear terminal from Python/Bash script?

os.system('clear') or clear in .sh

Cross-language scripting support

20

What’s a scenario where clear might reduce productivity?

In log capture scripts

Hides terminal scrollback history


🔹 3. sleep – Execution Control

#

Question

Answer / Example

Explanation

21

What does sleep 5 do?

Pauses for 5 seconds

Delays script execution

22

Can sleep handle fractions?

sleep 0.5

Yes, it supports floating-point

23

What does sleep 1m mean?

Sleeps for 1 minute

Supports suffixes like s, m, h

24

How to use sleep in retry logic?

`for i in {1..5}; do cmd


25

How to delay a background task?

sleep 10 && task.sh &

Defers execution asynchronously

26

What’s the purpose of using sleep between loop iterations?

Throttling, pacing, or animation

Useful in polling, dashboards

27

Can sleep be interrupted?

Yes, via CTRL+C or signal

Responds to SIGINT, etc.

28

How is sleep used in systemd service files?

ExecStartPre=/bin/sleep 5

Adds startup delay before main service

29

How to simulate a slow network request?

curl ...; sleep 3; curl ...

Introduces delay between dependent calls

30

When is sleep a bad idea in production scripts?

When hardcoded, without checks

Can cause indefinite delays in failure scenarios


🔸 4. Combined Real-World Scenarios

#

Question

Use Case

Example

31

Create a live terminal clock

Bash UI

while true; do clear; date; sleep 1; done

32

Log build start timestamp

CI/CD

echo "Build started at $(date)" >> build.log

33

Display progress dots

UX

for i in {1..5}; do echo -n "."; sleep 1; done

34

Add delay between steps

Pipeline

step1 && sleep 10 && step2

35

Print environment at runtime

Debugging

echo "PATH=$PATH"

36

Clear screen on login

User experience

Add clear to .bash_profile

37

Retry failed health check

Infra validation

until curl -s localhost:8080; do sleep 5; done

38

Delay script to wait for DB

Startup script

sleep 15; ./start-app.sh

39

Print conditional status

Logging

if [ $? -ne 0 ]; then echo "Failed"; fi

40

Time an operation

Performance

start=$(date +%s); ... ; end=$(date +%s); echo $((end - start))


🔹 5. Edge Cases & Trick Questions

#

Question

Answer / Example

Explanation

41

What happens on sleep 0?

No delay

Effectively a no-op

42

What happens on sleep abc?

Error: invalid time interval

Non-numeric input is invalid

43

Can echo output binary?

Yes, but limited

Use printf for control

44

What does echo -e "123\r456" do?

Overwrites output

\r returns cursor to line start

45

How to delay execution without sleep?

read -t 5

Waits for input for 5 seconds

46

Why avoid echo for structured output?

Use printf instead

Better formatting control

47

How to simulate clear effect without using clear?

printf "\033c"

ANSI reset sequence

48

How to show spinner using sleep?

spin='-|/'; while true; do ...; sleep 0.1; done

Visual loading animation

49

Why use echo with >> in deployment?

Logging progress

Tracks step-by-step execution

50

How to use all three (echo, clear, sleep) together?

Interactive UI

clear; echo "Loading..."; sleep 3


📦 Summary

Command

Best Use Cases

echo

Logging, debugging, output control

clear

UI, clean prompts, loop dashboards

sleep

Timing control, retry logic, pacing



 FAANG-Level Tricky Pathname Questions & Edge Cases (with Solutions)

#

Category

Question

Edge/Trick

✅ Solution / Explanation

1

Absolute vs Relative

What’s the difference between /etc/passwd and passwd?

One is fully qualified, the other depends on $PATH or pwd

/etc/passwd is absolute; passwd may fail unless present in current or $PATH directories

2

cd ..

What does cd .. do from /?

Root has no parent — cd .. stays in /

No error, but no movement occurs

3

Double slashes

What is the result of cd ////usr///bin?

Multiple slashes are collapsed

It’s equivalent to cd /usr/bin

4

. and ..

What does ls ./../././../etc resolve to?

Dot and dot-dot normalize to /etc

Simplifies to /etc through normalization

5

Symlink loop

What if a symlink points to itself?

Causes infinite resolution loop

Commands like readlink -f or ls -l will error

6

~ Expansion

What does echo "~user" do?

Quoted tilde prevents expansion

Outputs ~user, not the home dir

7

Trailing Slash

Difference between /var/log and /var/log/?

Usually none, but some scripts check trailing /

rsync behaves differently depending on presence of trailing /

8

Spaces in Paths

What happens with cd /home/user/My Documents?

Fails if not quoted

Must use cd "/home/user/My Documents"

9

$0 in Scripts

What does $0 represent in a script?

Path to script — may be relative or absolute

Use readlink -f "$0" for reliable full path

10

Quoting Errors

What does cd "$DIR" do if DIR="file 1"?

Works correctly — quoting prevents split

cd $DIR (unquoted) would break

11

$PWD vs pwd

Are $PWD and pwd always the same?

No — $PWD is shell-internal, pwd may resolve symlinks

Use pwd -P to get physical path

12

Subdir Access

Can you access /home/user/secret/ if secret/ has ---x--x--x perms?

You can cd but not ls

Execute-only allows traversal, not listing

13

Cron Path Error

Why might script.sh work in shell but fail in cron?

Cron lacks full $PATH and relative dirs

Use absolute paths always in cron jobs

14

. in $PATH

Is adding . to $PATH safe?

Dangerous — allows execution of unintended binaries in pwd

Never include . in $PATH on production systems

15

Loop Symlinks

What if A → B and B → A?

Circular symlinks — cause resolution failure

Tools like realpath detect and fail

16

readlink -f

What does readlink -f ./../dir return?

Canonical absolute path

Resolves symlinks and cleans relative components

17

basename

What does basename /usr/bin/env return?

Just env

Removes directory part

18

dirname

What does dirname /home/user/file.txt return?

/home/user

Returns everything but the last component

19

$HOME unset

What if cd ~ fails?

If $HOME is unset or invalid

cd ~ will error or go nowhere

20

Symlink to Parent

What if you cd symlink where symlink → ..?

You move up one level

Follows the target path just like any normal ..


🔍 Real-World Debug Scenarios

#

Scenario

Problem

Root Cause

Fix

21

Bash script using ../env.sh fails in Jenkins

Relative path fails

Jenkins changes working directory

Use source "$(dirname "$0")/../env.sh"

22

source ~/setup.sh fails in cron

~ is not expanded

Cron runs in minimal shell

Use $HOME/setup.sh or hardcode full path

23

./run.sh gives “No such file” but file exists

Wrong shell / CRLF

File has DOS line endings

Use dos2unix run.sh

24

Symbolic link to moved file broken

ln -s oldpath link → file moved

Link doesn't auto-update

Use ln -s $(realpath file) if predictable

25

Dockerfile COPY ./config /etc/config fails

Wrong build context

Path not visible in build context

Use relative paths from Docker build dir


🔧 Bonus Edge Behavior (Often Misunderstood)

Edge Case

Command

Behavior

cd ~nonexistentuser

Fails

No such user exists

cd /dev/null

Works but you're stuck

/dev/null is a character device, not a dir

ls --

Lists files named -

-- stops flag parsing

rm -rf /some/path/.*

Dangerous!

Removes .. too, deleting parent dir recursively

find . -name '../*'

Won’t match

find operates within current tree only


🧠 Summary Tips for FAANG Interviews

Topic

Insight

Always use readlink -f

Ensures canonical path

Avoid hardcoded relative paths

Breaks in CI/CD, containers

Prefer quoting "${PATH}"

Avoids word-splitting bugs

Know difference between logical and physical paths

$PWD vs pwd -P

Understand file permissions at directory level

x vs r on dirs





Distributed by Gooyaabi Templates | Designed by OddThemes