Operating Systems · UGC NET: Linux Operating System
Unix Commands and Shell Scripts
Overview
This topic covers the Unix/Linux shell as a command interpreter, the syntax of commands, standard streams, redirection, pipes, filters, file permissions, process priority, common utilities, and shell scripts.
It is examined through command-purpose questions, output prediction, permission arithmetic, matching of special parameters, and tracing short scripts.
Before studying it, know what files, directories, permissions, processes, and standard input/output mean. The shell does not itself perform most operations; it expands the command line and asks the kernel to run programs.
Key concepts
- Shell: command interpreter that reads a line, performs expansions, sets redirections and pipes, and executes commands.
Common shells are Bourne shellsh, C shellcsh, Korn shellksh, and Bash. “Not Shell” is not a Unix shell. - Command syntax:
command [options] [arguments]. Options usually begin with-. A semicolon;separates commands run sequentially;&runs a command in the background. - Standard streams: standard input
stdinis file descriptor 0, standard outputstdoutis 1, standard errorstderris 2. - Redirection:
<takes stdin from a file;>writes stdout to a file and truncates it;>>appends stdout;2>redirects stderr;2>&1sends stderr to the same place as stdout. - Pipe
|: connects stdout of the left command to stdin of the right command. Both commands run concurrently. Stderr is not piped unless redirected. - Filename generation or globbing: the shell expands
*,?,[abc],[a-z], and[!abc]before the command runs.*normally does not match names beginning with a dot. - Filters: commands that read stdin, transform it, and write stdout. Important filters are
grep,wc,sort,uniq,cut,tr,sed,awk,head,tail, andcat. - grep: “global regular expression print”. It prints matching lines.
-vinverts the match,-nprefixes line numbers,-iignores case,-ccounts matching lines,-llists filenames.
Thusgrep -vn "abc" fileprints nonmatching lines with line numbers. - wc: word count. Default reports lines, words, and bytes.
-lreports newline characters, i.e. line count;-wwords;-cbytes;-mcharacters. In ASCII text, bytes and characters coincide. - sort: rearranges input lines. Default is lexicographic order.
-nnumeric,-rreverse,-kchooses a key,-tsets the field delimiter.
Classical Unix usessort +nto skipnfields before sorting; GNU/POSIXsortuses 1-based-kpositions. UGC questions often use the classical+nform. - head and tail:
head -n Nprints the first N lines;tail -n Nprints the last N lines.tail -ffollows a growing file. - cut: extracts fields.
cut -d: -f3 fileuses colon as delimiter and prints the third field. Equivalent inawkisawk -F: '{print $3}' file. - sed: stream editor.
sed 's/old/new/g' filesubstitutes text globally on each line. - awk: record-and-field text processor;
$0is the whole record and$1,$2, … are fields. - tr: translates or deletes characters, e.g.
tr 'a-z' 'A-Z'. - seq: generates numbers. Syntax is
seq FIRST INCREMENT LAST.seq 1 2 10prints 1 3 5 7 9. - more and less: paginate output one screen at a time;
moreis the classical pager, conventionally about 24 lines per screen.catsimply concatenates and does not paginate. - pr and lpr:
prformats text for printing with headers and page breaks;lprsubmits a file to the printer. - rm: removes files. The shell expands wildcards before
rmsees the names, sorm report[1-3].txtremoves matching files if they exist. - mkdir: creates directories. A parent directory must already exist unless
-pis used. To createPIS, then its subdirectories, createPISfirst and thenPIS/progsandPIS/data. - File permissions: a 9-bit mode has three classes: user/owner, group, others. Each class has read
r, writew, executex.
Symbolicchmodusesu,g,o,a, operators+,-,=, and-Rfor recursive changes.chmod a+xadds execute for all;chmod ugo+xis equivalent by class list.chmod go-wremoves write from group and others. - nice and renice: nice value ranges from to . A lower nice value means higher CPU priority.
nicestarts a command with an adjusted niceness, default increment 10;renicechanges a running process.
Only root can reduce the nice value to increase priority. - Shell variables: assignment is
name=valuewith no spaces around=.$namereads it.
A local variable is not inherited by child processes;export namemakes it an environment variable inherited by children.echo -nsuppresses the newline;echo -iis not the standard no-newline option. - Special parameters:
$?is the exit status of the last command,$#is the number of positional arguments,$0is the script name,$1,$2, … are positional arguments,$*and$@expand to all positional parameters,$$is the current shell PID, and$!is the PID of the most recent background command. - test command:
test conditionor[ condition ]. String equality is=, inequality!=; numeric equality is-eq, inequality-ne, and so on. POSIX test uses=for strings, not==. - Control structures:
for var in word-list; do commands; done; alsowhile,until,if ... then ... fi, andcase ... esac. - vi editor: a modal editor.
In ex/command-line mode,:wwrites and stays,:xwrites and quits,:qquits,:q!quits without saving,:shescapes to a shell.vi file1 file2places both files in the argument list;:nmoves to the next file. - Process utilities:
pslists processes,killsends a signal,jobslists shell jobs,fgbrings a background job to the foreground, andbgcontinues a stopped job in the background. - Unix command names to recognise:
whoamiprints the current username,wccounts,lslists,lprprints, andputis not a standard Unix command.
How it works
- The shell reads the command line and splits it into words and operators.
- It performs expansions: aliases, variables, command substitution, arithmetic, and filename globbing. Globbing happens before the command program starts.
- It sets up redirections by opening files and duplicating file descriptors. For example,
2> errors.txtmakes file descriptor 2 point to that file. - For a pipeline, it creates a pipe, forks processes, and connects stdout of the left command to stdin of the right command.
- It executes the commands. Built-in commands such as
cd,export, andreadrun in the shell itself; external commands are run byforkandexec. - When a command finishes, its exit status is stored in
$?. Zero means success; nonzero means failure. - A shell script is a text file of commands. A shebang line such as
#!/bin/shselects the interpreter. Make the script executable withchmod +x script, then run it as./scriptorsh script. - File access is checked by the kernel against the file mode and the user’s uid/gid. Execute permission on a directory allows traversal; read permission lists names; write permission creates or removes entries.
nicesets niceness when a process starts;renicechanges it later. Normal users can usually only increase niceness, i.e. lower priority.
Drawing the diagram…
Formulas
-
For one permission class, the octal digit is
-
where indicate whether read, write and execute are present.
-
A three-digit mode is written as
-
where , , are the octal digits for user, group and others. Numerically,
-
Nice value satisfies
-
and a lower means higher priority. The default increment used by
nicewhen none is specified is 10.
Worked examples
Example 1: cut fields. File accounts.txt contains:
Ramesh:1001:5000
Geeta:1002:7000
Imran:1003:4500
Command:
cut -d: -f3 accounts.txt
-d: sets colon as delimiter; -f3 selects the third field. Output:
5000
7000
4500
Equivalent: awk -F: '{print $3}' accounts.txt.
Example 2: statement type. Statement I: wc -l reports the number of newline characters in its input. Statement II: sort rearranges input lines and writes to stdout unless redirected; it does not modify the input file by default.
Both statements are true. For a final line that lacks a newline, wc -l may not count it; this is the newline-count convention.
Example 3: sort by numeric key. File marks.txt:
Ankur 40 30
Pinki 20 90
Harish 30 50
Command:
sort -k2,2n marks.txt
This sorts by the second field numerically. Output:
Pinki 20 90
Harish 30 50
Ankur 40 30
Classical Unix equivalent is sort +1n: skip one field and numeric-sort the next field. Thus +10n skips ten fields and numeric-sorts the eleventh.
Example 4: permissions. chmod 641 mylife sets:
- user digit 6 =
rw-, so owner can read and write; - group digit 4 =
r--, so group can read; - other digit 1 =
--x, so others can execute only.
If a file has mode 664 and you run chmod go-w mylife, group write and other write are removed. The new mode is 644: owner rw-, group r--, other r--. chmod -R a+x progs adds execute permission for all classes to directory progs and everything below it.
Example 5: shell script trace.
#!/bin/sh
for n in one two three
do
echo -n "$n"
done
echo
export title=WELCOME
sh -c 'echo "$title"'
The loop prints without newlines: onetwothree. The following echo prints a newline. export title=WELCOME makes title an environment variable, so the child sh -c prints WELCOME. Final output:
onetwothree
WELCOME
Comparison
| Facility | Meaning | Common trap |
|---|---|---|
> | redirect stdout, truncate file | overwrites existing content |
>> | append stdout | does not truncate |
2> | redirect stderr | stdout still goes to terminal |
| ` | ` | pipe stdout to stdin |
grep -v | invert match | not “verbose” |
grep -n | prefix line numbers | not “numeric” |
wc -l | count newline characters or lines | not character count |
sort -n | numeric sort | default sort is lexicographic |
chmod go-w | remove write from group and others | go=w sets write only |
nice | start command with niceness | renice changes a running process |
$? | exit status of last command | not last process ID |
$! | PID of last background command | not $$, the shell PID |
| Parameter | Meaning |
|---|---|
$0 | name of the script or shell |
$1, $2, … | first, second, … positional arguments |
$# | number of positional arguments |
$* | all positional parameters as one expansion separated by IFS |
$@ | all positional parameters; quoted form preserves separate words |
$? | exit status of the most recent command |
$$ | PID of the current shell |
$! | PID of the most recent background command |
| Octal digit | Binary | Symbolic | Permission |
|---|---|---|---|
| 0 | 000 | --- | none |
| 1 | 001 | --x | execute |
| 2 | 010 | -w- | write |
| 3 | 011 | -wx | write and execute |
| 4 | 100 | r-- | read |
| 5 | 101 | r-x | read and execute |
| 6 | 110 | rw- | read and write |
| 7 | 111 | rwx | read, write and execute |
Revision summary
- The shell expands wildcards, variables and command substitution before running the command.
|connects stdout to stdin;2>handles stderr;&runs in the background.grep -vinverts,grep -nnumbers lines, andgrep -vndoes both.wcdefault prints lines, words and bytes;-llines,-cbytes,-mcharacters.- Classical
sort +nskipsnfields; GNUsort -kuses 1-based key positions. cut -d: -f3extracts the third colon-separated field;awk -F: '{print $3}'is equivalent.- Permission digit formula: read 4, write 2, execute 1.
641meansrw-,r--,--x. chmod -R a+xis recursive;chmod go-wremoves group and other write permission.- Nice range is highest priority to lowest priority; normal users can only increase niceness.
- A local shell variable is not inherited;
exportmakes it available to child processes. $?is exit status,$#argument count,$0script name,$!last background PID.for v in list; do ...; doneis the standard loop;echo -nsuppresses newline;putis not a standard Unix command.
Previous-year exam insights
- Direct concept questions ask the purpose of
wc,more,lpr,nice,mkdir,grep, and shell types. - Output-prediction questions use pipelines, semicolon-separated commands, background jobs, loops, and
seq. - Statement I/II/III questions test shell execution, local versus exported variables, permissions, and
nice. - Match-the-list questions commonly pair special parameters
$?,$#,$0,$*and vi ex commands:w,:x,:q,:sh. - Numeric permission questions require converting octal digits to
rwxand checking recursive-R. - Common traps are
grep -vversusgrep -n,wc -lversuswc -c,$!versus$?, and local versus exported variables. - For pipeline questions, first decide what each command reads and writes, then apply the filters left to right.
- Check shell syntax carefully: a
forloop needsin,do, anddone; string equality uses=, and numeric equality uses-eq.
Practice at PARIKSHA
You are ready for the PARIKSHA tests of this sub-topic when you can:
- identify the purpose and important options of
grep,wc,sort,cut,sed,awk, andtr; - trace a pipeline with redirection, globbing, and background execution;
- compute symbolic and octal
chmodmodes, including recursive changes; - explain
niceandrenicevalues and priority direction; - write and trace a
forloop, variable assignment,export, andecho -n; - distinguish local variables from environment variables;
- predict output of
head,tail,seq,wc, and semicolon-separated commands; - match shell special parameters and vi ex commands correctly;
- use
testoperators for string and numeric comparisons; - explain the 9-bit Unix file permission mode and its effect on files and directories.
Attempt the sub-topic test first, then the subject test.