III
Working with File Contents
Read, display, copy, manipulate and analyze file contents using Linux commands. Learn to use head, tail, cat, tac, cp, ls, more, strings and I/O redirection.
01
head
Display the first N lines of a file
display
▾
The head command outputs the beginning of a file. By default it shows the first 10 lines. Use the
-n flag (or -N shorthand) to specify a custom line count.
Syntax
$ head filename # first 10 lines (default) $ head -12 filename # first 12 lines $ head -n 12 filename # equivalent $ head -c 100 filename # first 100 bytes
Display first 12 lines of /etc/services
$ head -12 /etc/services
Task (a): Display the first 12 lines of
/etc/services — use head -12 /etc/services
02
tail
Display the last N lines of a file
display
▾
The tail command outputs the end of a file. The
-f flag (follow) keeps the file open and displays new lines as they are added — useful for monitoring log files in real time.
Syntax
$ tail filename # last 10 lines (default) $ tail -1 filename # last 1 line $ tail -f filename # follow (live updates) $ tail -n 20 filename # last 20 lines
Display last line of /etc/passwd
$ tail -1 /etc/passwd
Follow a file live (two-terminal task)
# Terminal 1 $ echo "this is the first line" > tailing.txt $ tail -f tailing.txt # Terminal 2 — append while tail is running $ echo "This is another line" >> tailing.txt
Task (b):
tail /etc/passwd shows the last line. Use >> (double chevron) to append without overwriting.
03
cat
Create, display and concatenate files
write
display
▾
cat (concatenate) is one of the most versatile Linux commands. It can create files with content (using
> redirection), display file contents, combine files, and append content using >>. A here document (<< WORD) lets you type multi-line input until the sentinel word is typed.
Syntax
$ cat filename # display file $ cat > newfile.txt # create file (type content, Ctrl+D to end) $ cat file1 file2 > combined.txt # concatenate into new file $ cat file1 >> file2 # append file1 to file2 # Here document — input ends when sentinel word is typed alone $ cat > tennis.txt << ace > Venus Williams > Serena Williams > ace # sentinel ends input
Task (c) — Create count.txt
$ cat > count.txt > one > two > three > ^D # Ctrl+D to save
Task (e) — Backup count.txt using cat
$ cat count.txt > catcnt.txt
Task (k) — Append /etc/passwd to tailing.txt
$ cat > tailing.txt $ cat /etc/passwd >> tailing.txt
Task (l) — Prepend /etc/passwd to tailing.txt
$ cat /etc/passwd > tailing.txt
04
cp
Copy files and directories
write
▾
cp copies files or directories. Use
-r for recursive directory copy. The task requires copying count.txt to cnt.txt as a backup.
Syntax
$ cp source destination $ cp -r sourcedir/ destdir/ # recursive (directories)
Task (d) — Backup count.txt to cnt.txt
$ cp count.txt cnt.txt
05
tac
Display file lines in reverse order
display
▾
tac is cat spelled backwards — it prints file contents with the last line first and the first line last.
Syntax
$ tac filename
Task (f) — Display catcnt.txt in reverse
$ tac catcnt.txt
06
more
Page through file contents interactively
display
▾
more is a pager — it displays one screen of content at a time. Press Space to advance a page, Enter to advance one line, and q to quit.
Syntax
$ more filename $ ls -l | more # pipe output to more
Task (g) — Page through /etc/services
$ more /etc/services
07
strings
Extract readable text from binary files
read
▾
strings scans a (typically binary) file and prints sequences of printable characters that are at least 4 characters long. Very useful for examining what text is embedded in executables.
Syntax
$ strings binary_file $ strings -n 8 binary_file # min string length 8
Task (h) — Readable strings from passwd binary
$ strings /usr/bin/passwd
08
ls -S
Sort directory listing by file size
display
▾
The
-S flag sorts ls output by file size (largest first). Piping into head -1 isolates the biggest file.
Syntax
$ ls -S directory/ # sort by size, largest first $ ls -lS directory/ # long listing, sorted by size
Task (i) — Find the biggest file in /etc
$ ls -S /etc | head -1
IV
Working with Shell Variables
Explore system-defined and user-defined shell variables. Use echo, env, set, export, unset and understand variable scope across parent and child shells.
Variables & Echo
01
echo
Print text or variable values to terminal
display
▾
echo prints text or variable values. Prefix variables with
$ to expand them. Use \$ to print a literal dollar sign. The -n flag suppresses the trailing newline; -e enables escape sequences.
Syntax
$ echo "Hello World" $ echo "Hello $USERNAME" # expand variable $ echo -n "enter your name: " # no trailing newline $ echo "Price is \$15" # escape dollar sign
Task (a) — Display Hello + username
$ echo -n "enter your name: " $ read username $ echo "Hello : $username" # Or using system variable directly: $ echo "hello $USERNAME"
Output
hello students
02
VAR=value
Assign a value to a shell variable
variable
▾
Variables are assigned with
NAME=value — no spaces around the = sign. Variable names are case-sensitive. User-defined variables can be up to 20 letters/digits/underscores. Access the value with $NAME or ${NAME}.
Syntax
varname=value # no spaces around = $ echo $varname # access value $ echo "Value is ${varname}" # braces for clarity
Task (a) — Create variable answer = 42
answer=42 $ echo $answer
Output
42
Task (b) — Copy $LANG to $MyLANG
LANG=shellScripting MyLANG=$LANG $ echo $MyLANG
Task (k) — Combine variables creatively
var_x=Dumb var_y=do $ echo ${var_x}le${var_y}re # Dumbledore
Output
Dumbledore
No spaces around
=: var=1 ✓ — var = 1 ✗ (bash sees it as a command named var)
03
env
List all current environment variables
env
▾
env (or
printenv) displays all exported environment variables currently set in the shell. These are variables available to child processes. Pipe to more for paged output.
Syntax
$ env # list all env vars $ env | more # paginate output $ echo $PATH # view specific variable
Task (d) — List all current shell variables
$ env
Common system-defined variables
BASH=/bin/bash HOME=/home/students LOGNAME=students PATH=/usr/bin:/sbin:/bin:/usr/sbin PWD=/home/students SHELL=/bin/bash USERNAME=students
04
set
Display all shell variables and set options
env
▾
set without arguments displays all shell variables (including local ones not exported). It also assigns environment variables. The
set -o option form enables shell options (e.g., noclobber).
Syntax
$ set # display all vars (incl. local) $ set | more # paginate $ set VARIABLE=value # assign a variable $ set PATH="/bin:/usr/bin:/usr/sbin:usr/local/bin"
Task (g) — Do env and set display your variable?
myVar=hello $ env | grep myVar # not found (not exported) $ set | grep myVar # found (set shows locals too)
env only shows exported variables. set shows all variables including local ones. A variable must be
export-ed to appear in env.
05
export
Mark variables for inheritance by child processes
env
▾
export marks a variable to be passed to any child process (sub-shell, script). Without export, a variable exists only in the current shell. Use
export -p to list all currently exported variables.
Syntax
$ export VARNAME # export existing variable $ export VARNAME=value # assign and export in one step $ export -p # list all exported variables # Append to existing variable (e.g. PATH) $ export PATH=$PATH:/home/user/bin
Task (e) — List all exported shell variables
$ export -p
Task (i) — Create two vars, export one
Var1=Ram Var2=Shyam $ export Var2 # only Var2 is exported
Task (j) — Display in child shell
$ bash # open child shell $ echo $Var1 # blank (not exported) $ echo $Var2 # Shyam (exported!) $ exit # return to parent $ echo $Var1 $Var2 # Ram Shyam (both visible here)
Variables set without
export: parent shell only. Variables set with export: parent + all child shells/scripts.
06
unset
Remove a variable from the shell environment
variable
▾
unset removes (destroys) a variable or function from the current shell environment. After unsetting, the variable evaluates to an empty string.
Syntax
$ unset VARNAME # remove variable $ echo $VARNAME # prints empty string
Task (h) — Destroy variable answer
answer=42 $ echo $answer # 42 $ unset answer $ echo $answer # (empty)
07
read
Read user input into a variable
variable
▾
read reads a line from standard input and assigns it to one or more variables. Combined with
echo -n it creates an interactive prompt.
Syntax
$ read varname # read one line into varname $ read -p "Prompt: " varname # prompt + read in one step
Task (a) — Interactive username input
$ echo -n "enter your name: " $ read username $ echo "Hello : $username"
08
PS1
Customize the shell prompt string
env
▾
PS1 is the system variable that controls the shell prompt. It supports backslash-escaped special characters. The task asks you to add the current time to your prompt.
Escape sequences
\u current username \h hostname (up to first dot) \W basename of current directory \w full current directory path \t time in 24-hr HH:MM:SS \T time in 12-hr HH:MM:SS \@ time in 12-hr am/pm \d date (Weekday Month Day) \$ $ for user, # for root \n newline
Task (l) — Add time to PS1 prompt
$ PS1='[\u@\h \W] \D{%F %T}\n\$ '
Resulting prompt looks like
[students@hostname ~] 2024-08-15 14:30:05 $