Bourne Shell Scripting/Appendix C: Quick Reference

From Wikibooks, open books for an open world
Jump to navigation Jump to search

This final section provides a fast lookup reference for the materials in this document. It is a collection of thumbnail examples and rules that will be cryptic if you haven't read through the text.

Useful commands[edit | edit source]

Command Effect
cat Lists a file or files sequentially.
cd Change directories.
chmod ugo+rwx Set read, write and execute permissions for user, group and others.
chmod a-rwx Remove read, write and execute permissions from all.
chmod 755 Set user write and universal read-execute permissions
chmod 644 set user write and universal read permissions.
cp Copy files.
expr 2 + 2 Add 2 + 2.
fgrep Search for string match.
grep Search for string pattern matches.
grep -v Search for no match.
grep -n List line numbers of matches.
grep -i Ignore case.
grep -l Only list file names for a match.
head -n5 source.txt List first 5 lines.
less View a text file one screen at a time; can scroll both ways.
ll Give a listing of files with file details.
ls Give a simple listing of files.
mkdir Make a directory.
more Displays a file a screenfull at a time.
mv Move or rename files.
paste f1 f2 Paste files by columns.
pg Variant on "more".
pwd Print working directory.
rm Remove files.
rm -r Remove entire directory subtree.
rmdir Remove an empty directory.
sed 's/txt/TXT/g' Scan and replace text.
sed 's/txt/d' Scan and delete text.
sed '/txt/q' Scan and then quit.
sort Sort input.
sort +1 Skip first field in sorting.
sort -n Sort numbers.
sort -r Sort in reverse order.
sort -u Eliminate redundant lines in output.
tail -5 source.txt List last 5 lines.
tail +5 source.txt List all lines after line 5.
tr '[A-Z]' '[a-z]' Translate to lowercase.
tr '[a-z]' '[A-Z]' Translate to uppercase.
tr -d '_' Delete underscores.
uniq Find unique lines.
wc Word count (characters, words, lines).
wc -w Word count only.
wc -l Line count.

Elementary shell capabilities[edit | edit source]

Command Effect
shvar="Test 1" Initialize a shell variable.
echo $shvar Display a shell variable.
export shvar Allow subshells to use shell variable.
mv $f ${f}2 or mv ${f}{,2} Append "2" to file name in shell variable.
$1, $2, $3, ... Command-line arguments.
$0 Shell-program name.
$# Number of arguments.
$* Complete argument list (all in one string).
$@ Complete argument list (string for every argument).
$? Exit status of the last command executed.
shift 2 Shift argument variables by 2.
read v Read input into variable "v".
. mycmds Execute commands in file.

IF statement[edit | edit source]

The if statement executes the command between if and then. If the command returns not 0 then the commands between then and else are executed - otherwise the command between else and fi.

   if test "${1}" = "red" ; then
     echo "Illegal code."
   elif test "${1}" = "blue" ; then
     echo "Illegal code."
     echo "Access granted."

   if [ "$1" = "red" ]
     echo "Illegal code."
   elif [ "$1" = "blue" ]
     echo "Illegal code."
     echo "Access granted."

Test Syntax Variations[edit | edit source]

Most test commands can be written using more than one syntax. Mastering and consistently using one form may be a programming best-practice, and may be a more efficient use of overall time.

String Tests[edit | edit source]

String Tests are performed by the test command. See help test for more details. To make scripts look more like other programming languages the synonym [ ... ] was defined which does exactly the same as test.

Command Effect
test "$shvar" = "red"

[ "$shvar" = "red" ]

String comparison, true if match.
test "$shvar" != "red"

[ "$shvar" != "red" ]

String comparison, true if no match.
test -z "${shvar}"

test "$shvar" = ""
[ "$shvar" = "" ]

True if null variable.
test -n "${shvar}"

test "$shvar" != ""
[ -n "$shvar" ]
[ "$shvar" != "" ]

True if not null variable.

Arithmetic tests[edit | edit source]

simple arithmetics can be performed with the test for more complex arithmetics the let command exists. See help let for more details. Note that for let command variables don't need to be prefixed with '$' and the statement need to be one argument, use '...' when there are spaces inside the argument. Like with test a synonym - (( ... )) - was defined to make shell scripts look more like ordinary programs.

Command Effect
test "$nval" -eq 0

let 'nval == 0'
[ "$nval" -eq 0 ]
(( nval == 0 ))

Integer test; true if equal to 0.
test "$nval" -ge 0

let 'nval >= 0'
[ "$nval" -ge 0 ]
(( nval >= 0 ))

Integer test; true if greater than or equal to 0.
test "$nval" -gt 0

let 'nval > 0'
[ "$nval" -gt 0 ]
(( nval > 0 ))

Integer test; true if greater than 0.
test "$nval" -le 0

let 'nval <= 0'
[ "$nval" -le 0 ]
(( nval <= 0 ))

Integer test; true if less than or equal to 0.
test "$nval" -lt 0

let 'nval < 0'
[ "$nval" -lt 0 ]
(( nval < 0 ))

Integer test; true if less than to 0.
test "$nval" -ne 0

let 'nval != 0'
[ "$nval" -ne 0 ]
(( nval != 0 ))

Integer test; true if not equal to 0.
let 'y + y > 100'

(( y + y >= 100))

Integer test; true when

File tests[edit | edit source]

Command Effect
test -d tmp

[ -d tmp ]

True if "tmp" is a directory.
test -f tmp

[ -f tmp ]

True if "tmp" is an ordinary file.
test -r tmp

[ -r tmp ]

True if "tmp" can be read.
test -s tmp

[ -s tmp ]

True if "tmp" is nonzero length.
test -w tmp

[ -w tmp ]

True if "tmp" can be written.
test -x tmp

[ -x tmp ]

True if "tmp" is executable.

Boolean tests[edit | edit source]

Boolean arithmetic is performed by a set of operators. It is important to note then the operators execute programs and compare the result codes. Because boolean operators are often combined with test command a unifications was created in the form of [[ ... ]].

Command Effect
test -d /tmp && test -r /tmp

[[ -d /tmp && -r /tmp ]]

True if "/tmp" is a directory and can be read.
test -r /tmp || test -w /tmp

[[ -r /tmp || -w /tmp ]]

True if "tmp" can be read or written.
test ! -x /tmp

[[ ! -x /tmp ]]

True if the file is not executable

CASE statement[edit | edit source]

   case "$1" 
     "red")      echo "Illegal code."
     "blue")     echo "Illegal code."
     "x"|"y")    echo "Illegal code."
     *)          echo "Access granted.";;

Loop statements[edit | edit source]

   for nvar in 1 2 3 4 5
     echo $nvar

   for file            # Cycle through command-line arguments.
     echo $file

   while [ "$n" != "Joe" ]     # Or:   until [ "$n" == "Joe" ]
     echo "What's your name?"
     read n
     echo $n

There are "break" and "continue" commands that allow you to exit or skip to the end of loops as the need arises.

Instead of [] we can use test. [] requires space after and before the brackets and there should be spaces between arguments.

Credit[edit | edit source]

This content was originally from and was originally in the public domain.