1. Gyanastra
  2. Operating Systems
  3. UGC NET: Linux Operating System
  4. Unix Commands and Shell Scripts
Free lesson, no account needed 13 min read 10 practice questions after it
Asked in past papers16 times
  • GATE CSE20041997
  • ISRO20172011
  • UGC NET201920182017201620152014201320122011200920072005

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 shell sh, C shell csh, Korn shell ksh, 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 stdin is file descriptor 0, standard output stdout is 1, standard error stderr is 2.
  • Redirection: < takes stdin from a file; > writes stdout to a file and truncates it; >> appends stdout; 2> redirects stderr; 2>&1 sends 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, and cat.
  • grep: “global regular expression print”. It prints matching lines. -v inverts the match, -n prefixes line numbers, -i ignores case, -c counts matching lines, -l lists filenames.
    Thus grep -vn "abc" file prints nonmatching lines with line numbers.
  • wc: word count. Default reports lines, words, and bytes. -l reports newline characters, i.e. line count; -w words; -c bytes; -m characters. In ASCII text, bytes and characters coincide.
  • sort: rearranges input lines. Default is lexicographic order. -n numeric, -r reverse, -k chooses a key, -t sets the field delimiter.
    Classical Unix uses sort +n to skip n fields before sorting; GNU/POSIX sort uses 1-based -k positions. UGC questions often use the classical +n form.
  • head and tail: head -n N prints the first N lines; tail -n N prints the last N lines. tail -f follows a growing file.
  • cut: extracts fields. cut -d: -f3 file uses colon as delimiter and prints the third field. Equivalent in awk is awk -F: '{print $3}' file.
  • sed: stream editor. sed 's/old/new/g' file substitutes text globally on each line.
  • awk: record-and-field text processor; $0 is 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 10 prints 1 3 5 7 9.
  • more and less: paginate output one screen at a time; more is the classical pager, conventionally about 24 lines per screen. cat simply concatenates and does not paginate.
  • pr and lpr: pr formats text for printing with headers and page breaks; lpr submits a file to the printer.
  • rm: removes files. The shell expands wildcards before rm sees the names, so rm report[1-3].txt removes matching files if they exist.
  • mkdir: creates directories. A parent directory must already exist unless -p is used. To create PIS, then its subdirectories, create PIS first and then PIS/progs and PIS/data.
  • File permissions: a 9-bit mode has three classes: user/owner, group, others. Each class has read r, write w, execute x.
    Symbolic chmod uses u, g, o, a, operators +, -, =, and -R for recursive changes. chmod a+x adds execute for all; chmod ugo+x is equivalent by class list. chmod go-w removes write from group and others.
  • nice and renice: nice value ranges from −20-20 to +19+19. A lower nice value means higher CPU priority. nice starts a command with an adjusted niceness, default increment 10; renice changes a running process.
    Only root can reduce the nice value to increase priority.
  • Shell variables: assignment is name=value with no spaces around =. $name reads it.
    A local variable is not inherited by child processes; export name makes it an environment variable inherited by children. echo -n suppresses the newline; echo -i is not the standard no-newline option.
  • Special parameters: $? is the exit status of the last command, $# is the number of positional arguments, $0 is 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 condition or [ 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; also while, until, if ... then ... fi, and case ... esac.
  • vi editor: a modal editor.
    In ex/command-line mode, :w writes and stays, :x writes and quits, :q quits, :q! quits without saving, :sh escapes to a shell. vi file1 file2 places both files in the argument list; :n moves to the next file.
  • Process utilities: ps lists processes, kill sends a signal, jobs lists shell jobs, fg brings a background job to the foreground, and bg continues a stopped job in the background.
  • Unix command names to recognise: whoami prints the current username, wc counts, ls lists, lpr prints, and put is not a standard Unix command.

How it works

  1. The shell reads the command line and splits it into words and operators.
  2. It performs expansions: aliases, variables, command substitution, arithmetic, and filename globbing. Globbing happens before the command program starts.
  3. It sets up redirections by opening files and duplicating file descriptors. For example, 2> errors.txt makes file descriptor 2 point to that file.
  4. For a pipeline, it creates a pipe, forks processes, and connects stdout of the left command to stdin of the right command.
  5. It executes the commands. Built-in commands such as cd, export, and read run in the shell itself; external commands are run by fork and exec.
  6. When a command finishes, its exit status is stored in $?. Zero means success; nonzero means failure.
  7. A shell script is a text file of commands. A shebang line such as #!/bin/sh selects the interpreter. Make the script executable with chmod +x script, then run it as ./script or sh script.
  8. 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.
  9. nice sets niceness when a process starts; renice changes it later. Normal users can usually only increase niceness, i.e. lower priority.
Figure. Notice the order: the shell parses the command line, handles expansion and redirection, then sends the left command's standard output through a pipe buffer to the right command's standard input. Final output goes to the terminal or an output file.

Formulas

  • For one permission class, the octal digit is d=4r+2w+x,d=4r+2w+x,

  • where r,w,x∈{0,1}r,w,x\in\{0,1\} indicate whether read, write and execute are present.

  • A three-digit mode is written as dudgdo,d_u d_g d_o,

  • where dud_u, dgd_g, dod_o are the octal digits for user, group and others. Numerically, M=82du+8dg+do.M=8^2 d_u+8d_g+d_o.

  • Nice value NN satisfies −20≤N≤+19,-20\le N\le +19,

  • and a lower NN means higher priority. The default increment used by nice when 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

FacilityMeaningCommon trap
>redirect stdout, truncate fileoverwrites existing content
>>append stdoutdoes not truncate
2>redirect stderrstdout still goes to terminal
``pipe stdout to stdin
grep -vinvert matchnot “verbose”
grep -nprefix line numbersnot “numeric”
wc -lcount newline characters or linesnot character count
sort -nnumeric sortdefault sort is lexicographic
chmod go-wremove write from group and othersgo=w sets write only
nicestart command with nicenessrenice changes a running process
$?exit status of last commandnot last process ID
$!PID of last background commandnot $$, the shell PID
ParameterMeaning
$0name 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 digitBinarySymbolicPermission
0000---none
1001--xexecute
2010-w-write
3011-wxwrite and execute
4100r--read
5101r-xread and execute
6110rw-read and write
7111rwxread, 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 -v inverts, grep -n numbers lines, and grep -vn does both.
  • wc default prints lines, words and bytes; -l lines, -c bytes, -m characters.
  • Classical sort +n skips n fields; GNU sort -k uses 1-based key positions.
  • cut -d: -f3 extracts the third colon-separated field; awk -F: '{print $3}' is equivalent.
  • Permission digit formula: read 4, write 2, execute 1. 641 means rw-, r--, --x.
  • chmod -R a+x is recursive; chmod go-w removes group and other write permission.
  • Nice range is −20-20 highest priority to +19+19 lowest priority; normal users can only increase niceness.
  • A local shell variable is not inherited; export makes it available to child processes.
  • $? is exit status, $# argument count, $0 script name, $! last background PID.
  • for v in list; do ...; done is the standard loop; echo -n suppresses newline; put is 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 rwx and checking recursive -R.
  • Common traps are grep -v versus grep -n, wc -l versus wc -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 for loop needs in, do, and done; 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, and tr;
  • trace a pipeline with redirection, globbing, and background execution;
  • compute symbolic and octal chmod modes, including recursive changes;
  • explain nice and renice values and priority direction;
  • write and trace a for loop, variable assignment, export, and echo -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 test operators 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.

Pages 1–2 of 2