Bash Programming For Linux
Bash Programming For Linux
com 1
Make an alias permanent
Use your favorite text editor to create a file called ~/.bash_aliases, and type the alias commands
into the file.
.bash_aliases will run at login (or you can just execute it with ..bash_aliases )
alias Details
Create an alias, aliases allow a string to be substituted for a word when it is used as the first word
of a simple command. The first word of each simple command, if unquoted, is checked to see if it has an alias. If so, that
Syntax word is replaced by the text of the alias. The alias name and the replacement text may contain any
alias [-p] [name[=value] ...]
unalias [-a] [name ... ]
valid shell input, including shell metacharacters, with the exception that the alias name may not
Key contain `='.
-p Print the current values
-a Remove All aliases The first word of the replacement text is tested for aliases, but a word that is identical to an alias
If arguments are supplied, an alias is defined for each name whose value is given. being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for
If no value is given, `alias' will print the current value of the alias. instance, and Bash does not try to recursively expand the replacement text.
Without arguments or with the `-p' option, alias prints the list of aliases on the standard output in If the last character of the alias value is a space or tab character, then the next command word
a form that allows them to be reused as input. following the alias is also checked for alias expansion.
name may not be `alias' or `unalias'.
unalias may be used to remove each name from the list of defined aliases. There is no mechanism for using arguments in the replacement text, as in csh. If arguments are
Examples needed, a shell function should be used . Aliases are not expanded when the shell is not
Create an alias 'ls' that will change the default action of ls: interactive, unless the expand_aliases shell option is set using shopt .
$ alias ls='ls --classify'
$ ls The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads
$ unalias ls at least one complete line of input before executing any of the commands on that line. Aliases are
More aliases for ls: expanded when a command is read, not when it is executed. Therefore, an alias definition
$ alias la='ls -lAXh --color=always' #Show all, sort by extension appearing on the same line as another command does not take effect until the next line of input is
$ alias ls-al='ls -al' #fix typo missing space read. The commands following the alias definition on that line are not affected by the new alias.
$ alias l="ls -l" This behavior is also an issue when functions are executed. Aliases are expanded when a function
$ alias la="ls -la" definition is read, not when the function is executed, because a function definition is itself a
Use alias to fix missing space typos: compound command. As a consequence, aliases defined in a function are not available until after
$ alias cd..='cd ..' that function is executed. To be safe, always put alias definitions on a separate line, and do not
$ alias ..='cd ..' use alias in compound commands.
Display the working directory `alias' and `unalias' are BASH built-ins. For almost every purpose, shell functions are preferred
$ alias .='echo $PWD' over aliases.
Prevent accidental deletions by making rm interactive: Search for and install software packages (Debian/Ubuntu).
$ alias rm='rm -i' Syntax
Shorten apt-get installation commands: apt-get [-sqdyfmubV] [-o= config_string ] [-c= config_file ]
[-t= target] update
$ alias canhaz='sudo apt-get install'
apt-get [-sqdyfmubV] [-o= config_string ] [-c= config_file ]
Run firefox and open a specific website: [-t= target] upgrade
$ alias fftr='/home/simon/firefox/firefox http://ss64.com' apt-get [-sqdyfmubV] [-o= config_string ] [-c= config_file ]
[-t= target] dselect-upgrade
Not every package listed on the command line has to be installed; remove, purge, hold, unhold, keep, reinstall
you can tell aptitude to do something different with a package by These commands are the same as “install”, but apply the named
appending an “override specifier” to the name of the package. For action to all packages given on the command line for which it is
example, aptitude remove wesnoth+ will install wesnoth, not remove not overridden. The difference between hold and keep is that hold
it. The following override specifiers are available:
will cause a package to be ignored by future safe-upgrade or
<package>+ full-upgrade commands, while keep merely cancels any scheduled
actions on the package. unhold will allow a package to be upgraded
Install <package>. by future safe-upgrade or full-upgrade commands, without otherwise
altering its state.
<package>+M
Install <package> and immediately mark it as automatically For instance, “aptitude remove '~ndeity'” will remove all packages
installed (note that if nothing depends on <package>, this will whose name contains “deity”.
cause it to be immediately removed).
markauto, unmarkauto
<package>-
This command is useful for avoiding broken versions of packages Unless you pass the -F option, the output of aptitude search will
without having to set and clear manual holds. If you decide you look something like this:
really want the forbidden version after all, the “install” command
will remove the ban. i apt - Advanced front-end for dpkg
pi apt-build - frontend to apt to build,
update optimize and in
Updates the list of available packages from the apt sources (this cp apt-file - APT package searching
is equivalent to “apt-get update”) utility -- command-
ihA raptor-utils - Raptor RDF Parser utilities
safe-upgrade
Each search result is listed on a separate line. The first
Upgrades installed packages to their most recent version. Installed character of each line indicates the current state of the package:
packages will not be removed unless they are unused (see the the most common states are p, meaning that no trace of the package
section “Managing Automatically Installed Packages” in the aptitude exists on the system, c, meaning that the package was deleted but
reference manual). Packages which are not currently installed may its configuration files remain on the system, i, meaning that the
be installed to resolve dependencies unless the --no-new-installs package is installed, and v, meaning that the package is virtual.
command-line option is supplied. The second character indicates the stored action (if any; otherwise
a blank space is displayed) to be performed on the package, with
It is sometimes necessary to remove one package in order to upgrade the most common actions being i, meaning that the package will be
another; this command is not able to upgrade packages in such installed, d, meaning that the package will be deleted, and p,
situations. Use the full-upgrade command to upgrade as many meaning that the package and its configuration files will be
show The command why finds a dependency chain that installs the package
named on the command line, as above. Note that the dependency that
Displays detailed information about one or more packages, listed aptitude produced in this case is only a suggestion. This is
following the search command. If a package name contains a tilde because no package currently installed on this computer depends on
character (“~”) or a question mark (“?”), it will be treated as a or recommends the kdepim package; if a stronger dependency were
search pattern and all matching packages will be displayed (see the available, aptitude would have displayed it.
section “Search Patterns” in the aptitude reference manual).
In contrast, why-not finds a dependency chain leading to a conflict
If the verbosity level is 1 or greater (i.e., at least one -v is with the target package:
present on the command-line), information about all versions of the
package is displayed. Otherwise, information about the “candidate $ aptitude why-not textopo
version” (the version that “aptitude install” would download) is i ocaml-core Depends ocamlweb
displayed. i A ocamlweb Depends tetex-extra | texlive-latex-
extra
You can display information about a different version of the i A texlive-latex-extra Conflicts textopo
package by appending =<version> to the package name; you can
display the version from a particular archive by appending If one or more <pattern>s are present, then aptitude will begin its
/<archive> to the package name. If either of these is present, then search at these patterns; that is, the first package in the chain
only the version you request will be displayed, regardless of the it prints will be a package matching the pattern in question. The
verbosity level. patterns are considered to be package names unless they contain a
tilde character (“~”) or a question mark (“?”), in which case they
If the verbosity level is 1 or greater, the package's architecture, are treated as search patterns (see the section “Search Patterns”
compressed size, filename, and md5sum fields will be displayed. If in the aptitude reference manual).
the verbosity level is 2 or greater, the select version or versions
will be displayed once for each archive in which they are found. If no patterns are present, then aptitude will search for
dependency chains beginning at manually installed packages. This
add-user-tag, remove-user-tag effectively shows the packages that have caused or would cause a
given package to be installed.
Adds a user tag to or removes a user tag from the selected group of
packages. If a package name contains a tilde (“~”) or question mark Note
(“?”), it is treated as a search pattern and the tag is added to or
removed from all the packages that match the pattern (see the aptitude why does not perform full dependency resolution; it
section “Search Patterns” in the aptitude reference manual). only displays direct relationships between packages. For
instance, if A requires B, C requires D, and B and C conflict,
User tags are arbitrary strings associated with a package. They can “aptitude why-not D” will not produce the answer “A depends on
be used with the ?user-tag(<tag>) search term, which will select B, B conflicts with C, and D depends on C”.
all the packages that have a user tag matching <tag>. By default aptitude outputs only the “most installed, strongest,
tightest, shortest” dependency chain. That is, it looks for a chain
why, why-not that only contains packages which are installed or will be
installed; it looks for the strongest possible dependencies under
Explains the reason that a particular package should or cannot be that restriction; it looks for chains that avoid ORed dependencies
installed on the system. and Provides; and it looks for the shortest dependency chain
meeting those criteria. These rules are progressively weakened
This command searches for packages that require or conflict with until a match is found.
the given package. It displays a sequence of dependencies leading
to the target package, along with a note indicating the installed If the verbosity level is 1 or more, then all the explanations
This corresponds to the configuration option For instance, aptitude safe-upgrade --remove-user-tag-from
Aptitude::CmdLine::Always-Prompt.
"not-upgraded,?action(upgrade)" will remove the not-upgraded tag
--purge-unused from all packages that the safe-upgrade command is able to upgrade.
Purge packages that are no longer required by any installed
package. This is equivalent to passing “-o -s, --simulate
Aptitude::Purge-Unused=true” as a command-line argument. In command-line mode, print the actions that would normally be
performed, but don't actually perform them. This does not require
-q[=<n>], --quiet[=<n>] root privileges. In the visual interface, always open the cache in
Suppress all incremental progress indicators, thus making the read-only mode regardless of whether you are root.
output loggable. This may be supplied multiple times to make the
program quieter, but unlike apt-get, aptitude does not enable -y This corresponds to the configuration option Aptitude::Simulate.
The optional =<n> may be used to directly set the amount of When package dependency problems are encountered, use a “safe”
quietness (for instance, to override a setting in algorithm to solve them. This resolver attempts to preserve as many
/etc/apt/apt.conf); it causes the program to behave as if -q had of your choices as possible; it will never remove a package or
been passed exactly <n> times. install a version of a package other than the package's default
candidate version. It is the same algorithm used in safe-upgrade;
-R, --without-recommends indeed, aptitude --safe-resolver full-upgrade is equivalent to
aptitude safe-upgrade. Because safe-upgrade always uses the safe
Do not treat recommendations as dependencies when installing new resolver, it does not accept the --safe-resolver flag.
packages (this overrides settings in /etc/apt/apt.conf and
~/.aptitude/config). Packages previously installed due to This option is equivalent to setting the configuration variable
recommendations will not be removed. Aptitude::Always-Use-Safe-Resolver to true.
This corresponds to the configuration option For instance, aptitude --schedule-only install evolution will
Apt::Install-Recommends schedule the evolution package for later installation.
This corresponds to the configuration item APT::Default-Release. This argument corresponds to the configuration option
Aptitude::CmdLine::Show-Why and displays the same information that
-V, --show-versions is computed by aptitude why and aptitude why-not.
This corresponds to the configuration option Specify the display width which should be used for output from the
Aptitude::CmdLine::Show-Versions. search command (by default, the terminal width is used).
aptitude will store its temporary files in the directory indicated –keymapping=name
by this environment variable. If TMPDIR is not set, then TMP will The keymapping to use. Either aspell for the default mapping or ispell to
be used; if TMP is also unset, then aptitude will use /tmp. use the same
mapping that the Ispell utility uses.
FILES
/var/lib/aptitude/pkgstates
The file in which stored package states and some package flags are
stored. Examples
Check the file foo.txt:
/etc/apt/apt.conf, /etc/apt/apt.conf.d/*, ~/.aptitude/config $ aspell check foo.txt
The configuration files for aptitude. ~/.aptitude/config overrides
/etc/apt/apt.conf. See apt.conf(5) for documentation of the format
Check the file foo.txt using the bad-spellers suggestion mode and the American English
and contents of these files. dictionary:
$ aspell check --sug-mode=bad-spellers -d en_US foo.txt
ENVIRON array of
names.
environment variables; subscripts are basename
Strip directory and suffix from filenames
In addition to simple pattern matching `awk' has a huge range of text and arithmetic Functions, Syntax
Variables and Operators. basename NAME [SUFFIX]
`gawk' will ignore newlines after any of the following:
, { ? : || && do else basename OPTION
Key
Comments - start with a `#', and continue to the end of the line: --help
# This program prints a nice friendly message Display help
Examples
Print the Row Number (NR), then a dash and space ("- ") and then the first item ($1) from each --version
line in samplefile.txt: Output version information and exit
$ awk '{print NR "- " $1 }' samplefile.txt basename will print NAME with any leading directory components removed. If specified, it will
Print the first item ($1) and then the third last item $(NF-2) from each line in samplefile.txt: also remove a trailing SUFFIX (typically a file extention).
$ awk '{print $1, $(NF-2) }' samplefile.txt Examples
Print every line that has at least one field. This is an easy way to delete blank lines from a file (or A script to rename file extensions:
rather, to #BatchRenameExt
create a new file similar to the old file but from which the blank lines have been deleted) for file in *.$1; do
awk 'NF > 0' data.txt mv $file `basename $file $1`.$2
Comparison with grep: done
Running grep Dec against the following file listing would return the 3 rows shown in bold as it $ BatchRenameExt htm html
matches text in different places:
-rw-r--r-- 7 simon simon 12043 Jan 31 09:36 December.pdf bc
-rw-r--r-- 3 simon simon 1024 Dec 01 11:59 README An arbitrary precision calculator language
-rw-r--r-- 3 simon simon 5096 Nov 14 18:22 Decision.txt Syntax
bc options file...
Running awk '$6 == "Dec"'against the same file listing, the relational operator $6 matches the
exact field (column 6 = Month) so it will list only the December file: Options:
$ ls -l /tmp/demo | awk '$6 == "Dec"' -h, --help
Print the usage and exit.
Print the length of the longest input line:
awk '{ if (length($0) > max) max = length($0) }
file A file containing the calculations/functions to perform.
END { print max }' data
May be piped from standard input
Print seven random numbers from zero to 100, inclusive:
builtin The word undergoes tilde expansion, parameter expansion, command substitution, arithmetic
Run a shell builtin, passing it args, and return its exit status. expansion, and quote removal before matching is attempted. Each pattern undergoes tilde
SYNTAX expansion, parameter expansion, command substitution, and arithmetic expansion. There may be
builtin [shell-builtin [args]]
an arbitrary number of case clauses, each terminated by a `;;'. The first pattern that matches
This is useful when defining a shell function with the same name as a shell builtin, retaining the
determines the command-list that is executed.
functionality of the builtin within the function.
For example, to write a function to replace `cd'
that writes the hostname and current directory Here is an example using case in a script that could be used to describe one interesting feature of
to an xterm title bar: an animal:
echo -n "Enter the name of an animal: "
cd() read ANIMAL
echo -n "The $ANIMAL has "
{ case $ANIMAL in
horse | dog | cat) echo -n "four";;
builtin cd "$@" && xtitle "$HOST: $PWD" man | kangaroo ) echo -n "two";;
*) echo -n "an unknown number of";;
} esac
The return status is non-zero if shell-builtin is not a shell builtin command. echo " legs."
cal
Bash programming for linux | nubielab.com 18
-P Do not follow symbolic links
cat If
-L Follow symbolic links (default)
directory is not given, the value of the HOME shell variable is used.
Display the contents of a file (concatenate)
Syntax
cat [Options] [File]... If the shell variable CDPATH exists, it is used as a search path.
If directory begins with a slash, CDPATH is not used.
Concatenate FILE(s), or standard input, to standard output.
-A, --show-all equivalent to -vET If directory is `-', this will change to the previous directory location (equivalent to $OLDPWD ).
-b, --number-nonblank number nonblank output lines
The return status is zero if the directory is successfully changed, non-zero otherwise.
-e equivalent to -vE Examples
-E, --show-ends display $ at end of each line Move to the sybase folder
-n, --number number all output lines $ cd /usr/local/sybase
$ pwd
-s, --squeeze-blank never more than one single blank line /usr/local/sybase
-t equivalent to -vT
Change to another folder
-T, --show-tabs display TAB characters as ^I $ cd /var/log
$ pwd
-u (ignored)
/var/log
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
Quickly get back
--help display this help and exit $ cd -
--version output version information and exit
$ pwd
/usr/local/sybase
With no FILE, or when FILE is -, read standard input.
Examples: move up one folder
$ cd ..
Display a file $ pwd
$ cat myfile.txt /usr/local/
Concatenate two files:
$ cat file1.txt file2.txt > union.txt $ cd (Back to your home folder)
If you need to combine two files but also eliminate duplicates, this can be done with sort unique:
$ sort -u file1.txt file2.txt > unique_union.txt cfdisk
Put the contents of a file into a variable Curses based disk partition table manipulator for Linux
$ my_variable=`cat $myfile.txt` Syntax
cfdisk [ -agvz ] [ -c cylinders ] [ -h heads ]
cd [ -s sectors-per-track ] [ -P opt ] [ device ]
Change Directory - change the current working directory to a specific Folder. Options
Syntax -a Use an arrow cursor instead of reverse video
cd [Options] [Directory] for highlighting the current partition.
Key
chgrp Options
Change group ownership -f, --silent, --quiet suppress most error messages
chown -f
--silent
Change owner, change the user and/or group ownership of each given File to a new Owner. --quiet
Chown can also change the ownership of a file to match the user/group of an existing reference Do not print error messages about files whose ownership cannot be
file. changed.
SYNTAX
chown [Options]... NewOwner File... -h
--no-dereference
chown [Options]... :Group File... Act on symbolic links themselves instead of what they point to.
This is the default. This mode relies on the `lchown' system call.
chown [Options]... --reference=RFILE File... On systems that do not provide the `lchown' system call, `chown'
fails when a file specified on the command line is a symbolic link.
If used, NewOwner specifies the new owner and/or group as follows By default, no diagnostic is issued for symbolic links encountered
(with no embedded white space): during a recursive traversal, but see `--verbose'.
-R
For files that are identical, `cmp' produces no output. When the files differ, by default, `cmp' OPTIONS
outputs the byte offset and line number where the first difference occurs. You can use the `-s' -P Use a default path
option to suppress that information, so that `cmp' produces no output and reports whether the files -v Verbose
-V More verbose
differ using only its exit status.
Only shell builtin commands or commands found by searching the PATH are executed. If there is a
Unlike `diff', `cmp' cannot compare directories; it can only compare two files.
shell function named ls, running `command ls' within the function will execute the external
comm command ls instead of calling the function recursively.
Common - compare two sorted files line by line and write to standard output:
the lines that are common, plus the lines that are unique. The `-p' option means to use a default value for $PATH that is guaranteed to find all of the
Syntax standard utilities. The return status in this case is 127 if command cannot be found or an error
comm [options]... File1 File2 occurred, and the exit status of command otherwise.
Options
-1 suppress lines unique to file1 If either the `-V' or `-v' option is supplied, a description of command is printed. The `-v'
-2 suppress lines unique to file2 option causes a single word indicating the command or file name used to invoke command to be
-3 suppress lines that appear in both files displayed; the `-V' option produces a more verbose description. In this case, the return status is
A file name of `-' means standard input. zero if command is found, and non-zero if not.
Before `comm' can be used, the input files must be sorted using the collating sequence specified
by the 'LC_COLLATE' locale, with trailing newlines significant. If an input file ends in a non- continue
newline character, a newline is silently appended. The 'sort' command with no options always Resume the next iteration of an enclosing for, while, until, or select loop.
SYNTAX
outputs a file that is suitable input to 'comm'. continue [n]
If n is supplied, the execution of the nth enclosing loop is resumed. n must be greater than or
With no options, `comm' produces three column output. Column one contains lines unique to equal to 1. The return status is zero unless n is not greater than or equal to 1.
FILE1, column two contains lines unique to FILE2, and column three contains lines common to Example
both files. Columns are separated by a single TAB character. for myloop in 1 2 3 4 5
do
The options -1, -2, and -3 suppress printing of the corresponding columns. if [ "$myloop" -eq 3 ]
then
continue # Skip rest of this particular loop iteration.
Unlike some other comparison utilities, `comm' has an exit status that does not depend on the fi
result of the comparison. Upon normal completion `comm' produces an exit code of zero. If there echo -n "$myloop"
is an error it exits with nonzero status. done
Examples
$ comm -23 <(sort words.txt | uniq) <(sort countries.txt | uniq)
cp
If the file words.txt contains a subset of countries.txt then the above will return nothing. Copy one or more files to another location
If the file words.txt contains items that don't exist in countries.txt then the above will return those
unique items. Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
Syntax
To return the lines that are in both words.txt and countries.txt use: cp [options]... Source Dest
$ comm -12 <(sort words.txt | uniq) <(sort countries.txt | uniq) cp [options]... Source... Directory
command Key
-f PREFIX Bytes, characters, and fields are are numbered starting at 1 and separated by commas.
--prefix=PREFIX Incomplete ranges may be given: -M means 1-M ; N- means N through end of line or last field.
Use PREFIX as the output file name prefix. Options
-b SUFFIX -b BYTE-LIST
--suffix=SUFFIX --bytes=BYTE-LIST
Use SUFFIX as the output file name suffix. When this option is Print only the bytes in positions listed in BYTE-LIST. Tabs and
specified, the suffix string must include exactly one backspaces are treated like any other character; they take up 1
`printf(3)'-style conversion specification, possibly including byte.
format specification flags, a field width, a precision
specifications, or all of these kinds of modifiers. The format -c CHARACTER-LIST
letter must convert a binary integer argument to readable form; --characters=CHARACTER-LIST
thus, only `d', `i', `u', `o', `x', and `X' conversions are Print only characters in positions listed in CHARACTER-LIST. The
allowed. The entire SUFFIX is given (with the current output file same as `-b' for now, but internationalization will change that.
number) to `sprintf(3)' to form the file name suffixes for each of Tabs and backspaces are treated like any other character; they
the individual output files in turn. If this option is used, the take up 1 character.
`--digits' option is ignored.
-f FIELD-LIST
-n DIGITS --fields=FIELD-LIST
--digits=DIGITS Print only the fields listed in FIELD-LIST. Fields are separated
Use output file names containing numbers that are DIGITS digits by a TAB character by default.
long instead of the default 2.
-d INPUT_DELIM_BYTE
-k --delimiter=INPUT_DELIM_BYTE
--keep-files For `-f', fields are separated in the input by the first character
Do not remove output files when errors are encountered. in INPUT_DELIM_BYTE (default is TAB).
-z -n
--elide-empty-files Do not split multi-byte characters (no-op for now).
Suppress the generation of zero-length output files. (In cases
where the section delimiters of the input file are supposed to -s
OPTIONS OPTIONS
The typeset command is supplied for compatibility with the Korn shell; however, it has been `-k'
deprecated in favor of the declare builtin command. `--kilobytes'
Print sizes in 1024-byte blocks, overriding the default block size.
The return status is zero unless an invalid option is encountered, an attempt is made to define a `-l'
function using `-f foo=bar', an attempt is made to assign a value to a readonly variable, an `--local'
`nfs' -c class
An NFS filesystem, i.e., one mounted over a network from Over-ride the default query class (IN for internet).
another machine. This is the one type name which seems to be class is any valid class, such as HS for Hesiod records or CH for
used uniformly by all systems. CHAOSNET records.
-v -r
This makes eject run in verbose mode; more information is displayed about what the command is This option specifies that the drive should be ejected using a CDROM eject command.
doing.
-s
-d This option specifies that the drive should be ejected using SCSI commands.
If invoked with this option, eject lists the default device name.
-f
-a on|1|off|0 This option specifies that the drive should be ejected using a removable floppy disk eject
This option controls the auto-eject mode, supported by some devices. When enabled, the drive command.
automatically ejects when the device is closed.
-q
-c <slot> This option specifies that the drive should be ejected using a tape drive offline command.
With this option a CD slot can be selected from an ATAPI/IDE CD-ROM changer. Linux 2.0 or
higher is required to use this feature. The CD-ROM drive can not be in use (mounted data CD or -p
playing a music CD) for a change request to work. Please also note that the first slot of the This option allow you to use /proc/mounts instead /etc/mtab. It also passes the -n option to
changer is referred to as 0, not 1. umount(1).
-t -m
With this option the drive is given a CD-ROM tray close command. Not all devices support this This option allows eject to work with device drivers which automatically mount removable media
command. and therefore must be always mount()ed. The option tells eject
to not try to unmount the given device, even if it is mounted according to /etc/mtab or
-T /proc/mounts.
With this option the drive is given a CD-ROM tray close command if it's opened, and a CD-ROM
tray eject command if it's closed. Not all devices support this command, because it uses the above -V
CD-ROM tray close command. This option causes eject to display the program version and exit.
Long Options
-x <speed> All options have corresponding long names, as listed below. The long names can be abbreviated
With this option the drive is given a CD-ROM select speed command. The speed argument is a as long as they are unique.
number indicating the desired speed (e.g. 8 for 8X speed), or 0 for maximum data rate. Not all -h --help
devices support this command and you can only specify speeds that the drive is capable of. Every -v --verbose
time the media is changed this option is cleared. This option can be used alone, or with the -t and -d --default
-c options. -a --auto
-c --changerslot
-X -t --trayclose
With this option the CD-ROM drive will be probed to detect the available speeds. The output is a -T --traytoggle
list of speeds which can be used as an argument of the -x option. This only works with Linux -x --cdspeed
2.6.13 or higher, on previous versions solely the maximum speed will be reported. Also note that -X --listspeed
eval export
Evaluate several commands/arguments Set an environment variable. Mark each name to be passed to child processes in the environment.
Syntax
Syntax
export [-fn] [-p] [name[=value]]
eval [arguments]
The arguments are concatenated together into a single command, which is then read and Options
executed, and its exit status returned as the exit status of eval. If there are no arguments or only -f The names refer to shell functions;
empty arguments, the return status is zero. otherwise the names refer to shell variables
-n No longer mark each name for export.
-p Display output in a form that may be reused as input.
eval is a POSIX `special' builtin If no names are supplied, or if the `-p' option is given, a list of exported names is displayed.
exec The return status is zero unless an invalid option is supplied, one of the names is not a valid shell
variable name, or `-f' is supplied with a name that is not a shell function.
Execute a command export is a BOURNE shell command and a POSIX `special' builtin.
Syntax
exec [-cl] [-a name] [command [arguments]]
Example - local variables
Options old_file=export.csv
-l Place a dash at the beginning of the zeroth arg passed to command. new_file=last.csv
(This is what the login program does.) mv $old_file $new_file
-c Causes command to be executed with an empty environment. Example - global variables
-a The shell passes name as the zeroth argument to command. mydepartment=Sales ; export mydepartment
If command is supplied, it replaces the shell without creating a new process. If no command is mycustomer='Brown Brothers' ; export mycustomer
specified, redirections may be used to affect the current shell environment.
fdisk
If there are no redirection errors, the return status is zero; otherwise the return status is non-zero. Partition table manipulator for Linux
exec is a BOURNE shell command and a POSIX `special' builtin Syntax
fdisk [-u] device
To run an executable file or a shell script from the command line it is often not necessary to use
exec at all, just prefix the filename with ./ fdisk -l [-u] device ...
bash will only search the path not the current working directory for the file.
To execute a program/script in the current working directory use: fdisk -s partition ...
./file_name fdisk -v
or
./ScriptName Options
-u When listing partition tables, give sizes in sectors instead of
cylinders.
You may be tempted to 'fix' this by adding '.' to $PATH but this is widely considered to be a bad
idea for security reasons. -l List the partition tables for /dev/hd[a-d], /dev/sd[a-h],
/dev/ed[a-d], and then exit.
exit -s partition
The partition is a device name followed by a partition it looks at the partition table, and tries to deduce what(fake) geometry is required for good
number. For example, /dev/hda1 is the first partition on cooperation with other systems.
the first IDE hard disk in the system. IDE disks can have
up to 63 partitions, SCSI disks up to 15. See also
/usr/src/linux/Documentation/devices.txt. Whenever a partition table is printed out, a consistency check is performed on the partition table
entries. This check verifies that the physical and logical start and end points are identical, and that
A BSD/SUN type disklabel can describe 8 partitions, the the partition starts and ends on a cylinder boundary (except for the first partition).
third of which should be a `whole disk' partition. Do not
start a partition that actually uses its first sector
(like a swap partition) at cylinder 0, since that will Some versions of MS-DOS create a first partition which does not begin on a cylinder boundary,
destroy the disklabel. but on sector 2 of the first cylinder. Partitions beginning in cylinder 1 cannot begin on a cylinder
boundary, but this is unlikely to cause difficulty unless you have OS/2 on your machine.
An IRIX/SGI type disklabel can describe 16 partitions, the
eleventh of which should be an entire `volume' partition,
while the ninth should be labeled `volume header'. The A sync() and a BLKRRPART ioctl() (reread partition table from disk) are performed before
volume header will also cover the partition table, i.e., exiting when the partition table has been updated. Long ago it used to be necessary to reboot after
it starts at block zero and extends by default over five the use of fdisk. I do not think this is the case anymore - indeed, rebooting too quickly might
xargs, will bundle up the files and (almost always) run them through a single instance of the Options
called program -- Pass all subsequent options to filesystem-specific checker.
find -exec, will run a separate instance of the called program for each file. All options that fsck doesn't recognize will also be passed.
Exit Status -r Interactive mode; prompt before making any repairs.
find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is
deliberately a very broad description, but if the return value is non-zero, you should not rely on -s Serial mode.
the correctness of the results of find.
-t fstype
As of findutils-4.2.2, shell metacharacters ('*'. '?' or '[]' for example) used in filename patterns Specify the filesystem type. Do not check filesystems of any other type.
will match a leading '.', because IEEE POSIX interpretation 126 requires this.
Non-bugs -A Check all filesystems listed in /etc/fstab.
$ find . -name *.c -print -N Suppress normal execution; just display what would be done.
find: paths must precede expression
Usage: find [-H] [-L] [-P] [path...] [expression] -R Meaningful only with -A: check all filesystems listed in /etc/fstab
except the root filesystem.
getopts Options
-A NUM
getopts is used by shell scripts to parse positional parameters. --after-context=NUM
Syntax Print NUM lines of trailing context after matching lines.
getopts optstring name [args] Places a line containing -- between contiguous groups of matches.
-a
Options --text
optstring : The option characters to be recognized Process a binary file as if it were text; this is equivalent
to the --binary-files=text option.
If a character is followed by a colon, the option is expected to
have an argument, which should be separated from it by white space. -B NUM
--quiet
hash
-q Remember the full pathnames of commands specified as name arguments, so they need not be
Suppress all warning messages. searched for on subsequent invocations.
SYNTAX
--recursive hash [-r] [-p filename] [name]
-r
Travel the directory structure recursively. If any of the file OPTIONS
names specified on the command line are directories, `gzip' will -r Reset (causes the shell to forget all remembered locations)
descend into the directory and compress all the files it finds -p Use filename as the location of name (don't search $PATH)
there (or decompress them in the case of `gunzip'). The commands are found by searching through the directories listed in $PATH.
--suffix SUF
-S SUF If no arguments are given, information about remembered commands is printed.
Use suffix `SUF' instead of `.gz'. Any suffix can be given, but
suffixes other than `.z' and `.gz' should be avoided to avoid
confusion when files are transferred to other systems. A null
The return status is zero unless a name is not found or an invalid option is supplied.
suffix forces gunzip to try decompression on all given files
regardless of suffix, as in: head
Output the first part of files, prints the first part (10 lines by default) of each file.
gunzip -S "" * (*.* for MSDOS) SYNTAX
head [options]... [file]...
-v With no options, display the history list with line numbers. Lines prefixed with with a `*' have
--verbose
Always print file name headers. been modified. An argument of n lists only the last n lines.
If no files are given (or if given a FILE of '-') head will read from standard input. When any of the `-w', `-r', `-a', or `-n' options are used, if filename is given, then it is used as the
If more than one FILE is specified, 'head' will print a one-line header consisting of ==> FILE history file. If not, then the value of the HISTFILE variable is used.
NAME <== before the output for each FILE. Recalling a previous command
Pressing the UP arrow will return to previous commands.
Two option formats are accepted: the new one, in which numbers are arguments to the options ('-
q -n 1'), and the old one, in which the number precedes any option letters ('-1q') To return to a previously entered command, type ctrl-r and then begin typing the command. This
Examples will finish the command for you as you type. If you can remember to use ctrl-r, it will become
Extract the first 85 lines from a file: invaluable for repeating longer commands.
head -85 file,txt
Extract lines 40-50 from a file, first using head to get the first 50 lines then tail to get the last 10: To find a specific command among many previous commands; pipe history through grep:
head -50 file.txt | tail -10 history|grep -i first few letters of command
!-n Refer to the command n lines back. x- Abbreviates `x-$' like `x*', but omits the last word.
!! Refer to the previous command. This is a synonym for `!-1'. If a word designator is supplied without an event specification,
the previous command is used as the event.
!string Refer to the most recent command starting with string. Modifiers
!?string[?] Refer to the most recent command containing string. After the optional word designator, you can add a sequence of one or more of the following
The trailing `?' may be omitted if the string is followed
immediately by a newline. modifiers, each preceded by a `:'.
h Remove a trailing pathname component, leaving only the head.
^string1^string2^ Quick Substitution. Repeat the last command, replacing
string1 t Remove all leading pathname components, leaving the tail.
with string2. Equivalent to !!:s/string1/string2/.
r Remove a trailing suffix of the form `.suffix', leaving the basename.
!# The entire command line typed so far.
e Remove all but the trailing suffix.
Word Designators
p Print the new command but do not execute it.
Word designators are used to select desired words from the event. A `:' separates the event
specification from the word designator. It may be omitted if the word designator begins with a `^', q Quote the substituted words, escaping further substitutions.
`$', `*', `-', or `%'. Words are numbered from the beginning of the line, with the first word being x Quote the substituted words as with `q', but break into words at
denoted by 0 (zero). Words are inserted into the current line separated by single spaces. spaces, tabs, and newlines.
For example,
--widechar-subst=formatstring
−s -r
−−silent --real
Suppress error messages about invalid or unconvertible characters Print the real, instead of effective, user or group id.
are omitted Requires -u, -g, or -G
--verbose -u
Print progress information. --user
The iconv program converts the encoding of characters in inputfile from one coded character set Print only the user id.
to another. The result is written to standard output unless otherwise specified by the --output
option. if
Examples Conditionally perform a command.
SYNTAX
Convert input.txt from ISO-8859-1 to UTF-8 and save as output.txt if test-commands; then
$ iconv -f ISO-8859-1 -t UTF-8 < input.txt > output.txt consequent-commands;
Script to convert all .HTML files in a directory from Windows 1242 to UTF8 (from [elif more-test-commands; then
brianwc/ShareAlike) more-consequents;]
[else alternate-consequents;]
#/bin/bash fi
LIST=`ls *.html` The test-commands list is executed, and if its return status is zero, the consequent-commands list
for i in $LIST; is executed.
do iconv -f WINDOWS-1252 -t UTF8 $i -o $i."utf8"; If test-commands returns a non-zero status, each elif list is executed in turn, and if its exit status
mv $i."utf8" $i; is zero, the corresponding more-consequents is executed and the command completes.
done
id If `else alternate-consequents' is present, and the final command in the final if or elif
clause has a non-zero exit status, then alternate-consequents is executed.
Print real and effective user id (uid) and group id (gid), prints identity information about the given
user, or if no user is specified the current process. The return status is the exit status of the last command executed, or zero if no condition tested
SYNTAX
id [options]... [username] true.
By default, it prints the real user id, real group id, effective user id if different from the real user
id, effective group id if different from the real group id, and supplemental group ids. ifconfig
Interface configurator - display your ip address, network interfaces, transferred and received data
Each of these numeric values is preceded by an identifying string and followed by the information, configure a network interface.
Syntax
corresponding user or group name in parentheses. ifconfig [interface]
OPTIONS
The options cause `id' to print only part of the above information.
ifconfig interface [aftype] options | address ...
-g
Options
--group
interface The name of the interface.
Print only the group id.
mtu N Set the Maximum Transfer Unit (MTU) of an interface. hw class address Set the hardware address of this interface, if the device
driver supports
dstaddr addr Set the remote IP address for a point-to-point (PPP)link this operation. The keyword must be followed by the name
(obsolete; use pointopoint instead) of the hardware class
and the printable ASCII equivalent of the hardware
netmask addr Set the IP network mask for this interface. address. Hardware classes
This value defaults to the usual class A, B or C network mask currently supported include ether (Ethernet), ax25 (AMPR
(as derived from the interface IP address), but it can be set AX.25), ARCnet and
to any value. netrom (AMPR NET/ROM).
add addr/prefixlen Add an IPv6 address to an interface. multicast Set the multicast flag on the interface. Not normally be
needed as
del addr/prefixlen Remove an IPv6 address from an interface. the drivers set the flag correctly themselves.
tunnel aa.bb.cc.dd Create a new SIT (IPv6-in-IPv4) device, tunnelling to address The IP address to be assigned to this interface.
the given destination.
txqueuelen length Set the length of the transmit queue of the device.
irq addr Set the interrupt line used by this device. It is useful to set this to small values for slower
Not all devices can dynamically change their IRQ setting. devices with a high
latency (modem links, ISDN) to prevent fast bulk transfers
io_addr addr Set the start address in I/O space for this device. from disturbing
interactive traffic like telnet too much.
mem_start addr Set the start address for shared memory used by this device. ifconfig is used at boot time to set up interfaces as necessary. After that, it is usually only needed
Only a few devices need this.
when debugging or when system tuning is needed.
media type Set the physical port or medium type to be used by the device. If no arguments are given, ifconfig displays the status of the currently active interfaces. If a single
Not all devices can change this setting, and those that can interface argument is given, it displays the status of the given interface only; if a single -a
vary argument is given, it displays the status of all interfaces, even those that are down. Otherwise, it
in what values they support. Typical values for type are
10base2 (thin Ethernet), configures an interface.
10baseT (twisted-pair 10Mbps Ethernet), AUI (external If the first argument after the interface name is recognized as the name of a supported address
transceiver) and so on. family, that address family is used for decoding and displaying all protocol addresses. Currently
DESCRIPTION -p
The 3 variants above install either a single SOURCE file to DEST target --preserve-timestamps
or copy multiple SOURCE files to the destination. In the last variant, Set the time of last access and the time of last modification of
each DIRECTORY (and any missing parent directories) is created. each installed file to match those of each corresponding original
file. When a file is installed without this option, its last
`install' is similar to `cp', but allows you to control the access and last modification times are both set to the time of
attributes of destination files. It is typically used in Makefiles to installation. This option is useful if you want to use the last
copy programs into their destination directories. It refuses to copy modification times of installed files to keep track of when they
files onto themselves. were last built as opposed to when they were last installed.
OPTIONS -s
--strip
-b Strip the symbol tables from installed binary executables.
--backup
Make a backup of each file that would otherwise be overwritten or -S SUFFIX
removed. *Note Backup options::. --suffix=SUFFIX
Append SUFFIX to each backup file made with `-b'.
-C
Install file, unless target already exists and is the same file, -v
in which case the modification time is not changed. --verbose
Print the name of each file before copying it.
-c
Ignored; for compatibility with old Unix versions of `install'. -V METHOD
--version-control=METHOD
-d Change the type of backups made with `-b'. The METHOD argument
--directory can be `numbered' (or `t'), `existing' (or `nil'), or `never' (or
Create each given directory and any missing parent directories, `simple').
setting the owner, group and mode as given on the command line or SysAdmins can't be sued for malpractice but surgeons don't have to deal with patients who install
to the defaults. It also gives any parent directories it creates new versions of their own innards.
those attributes. (This is different from the SunOS 4.x
`install', which gives directories that it creates the default
attributes.)
jobs
Print currently running jobs and their status.
-g GROUP Syntax
--group=GROUP jobs [OPTIONS] [PID]
-h `-i'
--help Display a help message and exit `--ignore-case'
Ignore differences in case when comparing keys. With this option,
-l the lines of the input files must be ordered in the same way. Use
--last Only the last job to be started is printed `sort -f' to produce this ordering.
-p `-1 FIELD'
--pid Print the process id for each process in all jobs `-j1 FIELD'
On systems that supports this feature, jobs will print the CPU usage of each job since the last Join on field FIELD (a positive integer) of file 1.
command was executed. The CPU usage is expressed as a percentage of full CPU activity. Note `-2 FIELD'
that on multiprocessor systems, the total activity may be more than 100%. `-j2 FIELD'
Example Join on field FIELD (a positive integer) of file 2.
`-j FIELD'
$ jobs Equivalent to `-1 FIELD -2 FIELD'.
The return status is true if at least one signal was successfully sent, or false if an error occurs or -l List all known signal names.
--list
an invalid option is encountered.
Examples name The command/process to be killed
List the running process
$ ps -q Do not complain if no processes were killed.
PID TTY TIME CMD --quiet
1293 pts/5 00:00:00 MyProgram
-r Interpret process name pattern as an extended regular expression.
Then Kill it --regexp
$ kill 1293
[2]+ Terminated MyProgram
-s signal
To run a command and then kill it after 5 seconds: --signal signal
$ my_command & sleep 5 Send signal instead of the default SIGTERM. e.g. -9 = SIGKILL
$ kill -0 $! && kill $!
-u user
kill is a bash built in command: $ help kill --user user
Kill only processes the specified user owns. Command names are
killall optional.
kill processes by name .
Syntax -v Report if the signal was successfully sent.
killall [option(s)] [--] name ... --verbose
-Z pattern
--context pattern
less
Display output one screen at a time, Search through output, Edit the command line.
Specify security context: kill only processes having security context SYNTAX
that match less [options]
with given expended regular expression pattern. Must precede other
arguments on <command> | less [options]
the command line. Command names are optional. (SELinux Only)
Moving Commands:
-- Each parameter after a '--' parameter is always interpreted as a non-
option parameter. Commands marked with * may be preceded by a number, N.
killall sends a signal to all processes running any of the specified commands. If no signal name is Notes in parentheses indicate the behavior if N is given.
specified, SIGTERM is sent.
Signals can be specified either by name (e.g. -HUP) or by number (e.g. -1) or by option -s. e ^E j ^N CR * Forward one line (or N lines).
y ^Y k ^K ^P * Backward one line (or N lines).
If the command name is not regular expression (option -r) and contains a slash (/), processes f ^F ^V SPACE * Forward one window (or N lines).
executing that particular file will be selected for killing, independent of their name. b ^B ESC-v * Backward one window (or N lines).
killall returns a zero return code if at least one process has been killed for each listed command, z * Forward one window (and set window to N).
or no commands were listed and at least one process matched the -u and -Z search criteria. killall w * Backward one window (and set window to N).
ESC-SPACE * Forward one window, but don't stop at end-of-file.
returns non-zero otherwise. d ^D * Forward one half-window (and set half-window to N).
A killall process never kills itself (but may kill other killall processes). u ^U * Backward one half-window (and set half-window to N).
Common kill signals ESC-( RightArrow * Left 8 character positions (or N positions).
ESC-) LeftArrow * Right 8 character positions (or N positions).
Signal name Signal value Effect F Forward forever; like "tail -f".
r ^R ^L Repaint screen.
SIGHUP 1 Hangup R Repaint screen, discarding buffered input.
SIGINT 2 Interrupt from keyboard h H Display this help.
SIGKILL 9 Kill signal q :q Q :Q ZZ Exit.
---------------------------------------------------
SIGTERM 15 Termination signal (allow the process to run it's exit handler) Default "window" is the screen height.
Default "half-window" is half of the screen height.
SIGSTOP 17,19,23 Stop the process
---------------------------------------------------------------------------
Files
/proc Searching Commands:
location of the proc file system
Known Bugs /pattern * Search forward for (N-th) matching line.
?pattern * Search backward for (N-th) matching line.
Typing killall name may not have the desired effect on non-Linux systems, especially when done n * Repeat previous search (for N-th occurrence).
by a privileged user. e.g. on Solaris it will kill all active processes. N * Repeat previous search in reverse direction.
Killing by file only works for executables that are kept open during execution, i.e. impure ESC-n * Repeat previous search, spanning files.
executables can't be killed this way. ESC-N * Repeat previous search, reverse dir. & spanning files.
ESC-u Undo (toggle) search highlighting.
-f ........
Don't automatically allocate buffers for pipes.
--force
let
Force open non-regular files. Perform arithmetic on shell variables.
-k [file] . --lesskey-file=[file] Syntax
Use a lesskey file. let expression [expression]
-o [file] . --log-file=[file] Each expression is an arithmetic expression to be evaluated. If the last expression evaluates to 0,
Copy to log file (standard input only). let returns 1; otherwise 0 is returned.
-O [file] . --LOG-FILE=[file]
Copy to log file (unconditionally overwrite).
`let' is a bash builtin command.
MISC OPTIONS:
-d ........--dumb
ln
Dumb terminal. Make links between files, by default, it makes hard links; with the `-s' option, it makes symbolic
-e -E .... --quit-at-eof --QUIT-AT-EOF (or "soft") links.
Quit at end of file. Syntax
-q -Q .... --quiet --QUIET --silent --SILENT ln [Options]... target [Linkname]
Quiet the terminal bell.
-u -U .... --underline-special --UNDERLINE-SPECIAL ln [Options]... target... Directory
Change handling of backspaces.
-x [N] .... --tabs=[N] Options
Set tab stops. -b
-X ........ --no-init --backup
Don't use termcap init/deinit strings. Make a backup of each file that would otherwise be overwritten or
-" [c[c]] . --quotes=[c[c]] removed. *Note Backup options::.
Set shell quote characters.
-? ........ --help -d
Display help (from command line). -F
-V ........ --version --directory
Display the version number of "less". Allow the super-user to make hard links to directories.
---------------------------------------------------------------------------
-f
Line Editing: --force
Remove existing destination files.
These keys can be used to edit text being entered
on the "command line" at the bottom of the screen. -i
--interactive
RightArrow ESC-l Move cursor right one character. Prompt whether to remove existing destination files.
LeftArrow ESC-h Move cursor left one character.
When the destination is an actual directory (not a symlink to one), "Symbolic links" ("symlinks" for short), on the other hand, are a special file type (which not all
there is no ambiguity. The link is created in that directory.
But when the specified destination is a symlink to a directory, kernels support: System V release 3 (and older) systems lack symlinks) in which the link file
there are two ways to treat the user's request. `ln' can treat actually refers to a different file, by name. When most operations (opening, reading, writing, and
the destination just as it would a normal directory and create the so on) are passed the symbolic link file, the kernel automatically "dereferences" the link and
link in it. On the other hand, the destination can be viewed as a operates on the target of the link. But some operations (e.g., removing) work on the link file itself,
non-directory--as the symlink itself. In that case, `ln' must
delete or backup that symlink before creating the new link. The rather than on its target.
default is to treat a destination that is a symlink to a directory Examples
just like a directory. $ ln file1.txt link1
$ rm file1.txt #The file cannot be deleted until the link is removed.
-s
--symbolic $ ln -s /some/name # create a link ./name pointing to /some/name
Make symbolic links instead of hard links. This option merely $ ln -s /some/name mylink2 # or give the link a name
produces an error message on systems that do not support symbolic
links. $ ln -s /home/simon/demo /home/jules/mylink3 #Create mylink3 pointing to demo
* If two filenames are given, `ln' creates a link from the second to the first. The return status is zero unless local is used outside a function, an invalid name is supplied, or
name is a readonly variable.
* If one TARGET is given, `ln' creates a link to that file in the current directory. `local' is a BASH builtin command.
* It is an error if the last argument is not a directory and more than two files are given. Without `- locate
f' or `-i' (see below), `ln' will not remove an existing file. Use the `--backup' option to make `ln' Find files.
rename existing files. Syntax
locate [options] pattern
A "hard link" is another name for an existing file; the link and the original are indistinguishable. Options
Technically speaking, they share the same inode, and the inode contains all the information about
exit DESCRIPTION
quit Exit from lpc. Lpr uses a spooling daemon to print the named files when facilities become
available. If no names appear, the standard input is assumed.
restart { all | printer } The following single letter options are used to notify the line printer
Attempt to start a new printer daemon. This is useful when some spooler that the files are not standard text files. The spooling daemon
abnormal condition causes the daemon to die unexpectedly leaving will use the appropriate filters to print the data accordingly.
jobs in the queue. Lpq will report that there is no daemon present
when this condition occurs. If the user is the super-user, -c The files are assumed to contain data produced by cifplot(1)
try to abort the current daemon first (i.e., kill and restart a
stuck daemon). -d The files are assumed to contain data from tex (DVI format from
Stanford).
start { all | printer }
Enable printing and start a spooling daemon for the listed printers. -f Use a filter which interprets the first character of each line as
a standard FORTRAN carriage control character.
status { all | printer }
Display the status of daemons and queues on the local machine. -g The files are assumed to contain standard plot data as produced
by the plot routines (see also plot for the filters used by the
stop { all | printer } printer spooler).
Stop a spooling daemon after the current job completes and disable
printing. -l Use a filter which allows control characters to be printed and
suppresses page breaks.
topq printer [ jobnum ... ] [ user ... ]
Place the jobs in the order listed at the top of the printer
-s Use symbolic links. Usually files are copied to the spool -wnum Uses num as the page width for pr(1).
directory.
The -s option will use symlink(2) to link data files Environment
rather than trying to copy them so large files can be printed. If the following environment variable exists, it is used by lpr:
This means the files should not be modified or removed until they
have been printed. PRINTER Specifies an alternate default printer.
The remaining options apply to copies, the page display, and headers: Files
/etc/passwd Personal identification.
-#num The quantity num is the number of copies desired of each file /etc/printcap Printer capabilities data base.
named. For example, /usr/sbin/lpd* Line printer daemons.
/var/spool/output/* Directories used for spooling.
lpr -#3 foo.c bar.c more.c /var/spool/output/*/cf* Daemon control files.
/var/spool/output/*/df* Data files specified in "cf" files.
would result in 3 copies of the file foo.c, followed by 3 copies /var/spool/output/*/tf* Temporary copies of "cf" files.
of the file bar.c, etc. On the other hand,
Diagnostics
cat foo.c bar.c more.c | lpr -#3 If you try to spool too large a file, it will be truncated. Lpr will object
to printing binary files. If a user other than root prints a file
will give three copies of the concatenation of the files. Often a and spooling is disabled, lpr will print a message saying so and will not
site will disable this feature to encourage use of a photocopier put jobs in the queue. If a connection to lpd(1) on the local machine
instead. cannot be made, lpr will say that the daemon cannot be started. Diagnostics
may be printed in the daemon's log file regarding missing spool
-[1234]font files by lpd(1).
Specifies a font to be mounted on font position i. The daemon
will construct a .railmag file referencing the font pathname. Bugs
Fonts for troff(1) and tex reside on the host with the printer. It is
-C class currently not possible to use local font libraries.
Job classification to use on the burst page. For example,
-Pprinter ERROR Messages: `Permission denied' if the user tries to remove files other than their own.
Specify the queue associated with a specific printer (otherwise
the default printer is used).
ls
- If a single `-' is given, lprm will remove all jobs which a user List information about files.
owns. If the super-user employs this flag, the spool queue will Syntax
be emptied entirely. ls [Options]... [File]...
user Causes lprm to attempt to remove any jobs queued belonging to Key
that user (or users). This form of invoking lprm is useful only Sort entries alphabetically if none of -cftuSUX nor --sort.
to the super-user.
-a, --all Do not hide entries starting with .
job# A user may dequeue an individual job by specifying its job number.
This number may be obtained from the lpq(1) program, e.g. -A, --almost-all Do not list implied . and ..
If neither arguments or options are given, lprm will delete the currently -c Sort by change time; with -l: show ctime
active job if it is owned by the user who invoked lprm.
-C List entries by columns
lprm announces the names of any files it removes and is silent if there
are no jobs in the queue which match the request list. --color[=WHEN] Control whether color is used to distinguish file
types. WHEN may be `never', `always', or `auto'
lprm will kill off an active daemon, if necessary, before removing any
spooling files. If a daemon is killed, a new one is automatically -d, --directory List directory entries instead of contents
restarted upon completion of file removals.
-D, --dired Generate output designed for Emacs' dired mode
Environment
If the following environment variable exists, it is utilized by lprm. -f Do not sort, enable -aU, disable -lst
PRINTER If the environment variable PRINTER exists, and a printer has -F, --classify Append indicator (one of */=@|) to entries
not been specified with the -P option, the default printer is
assumed from PRINTER. --format=WORD Across -x, commas -m, horizontal -x, long -l,
single-column -1, verbose -l, vertical -C
Files
/etc/printcap Printer characteristics file. --full-time List both full date and full time
/var/spool/* Spooling directories.
/var/spool/*/lock Lock file used to obtain the pid of the current daemon -g (ignored)
and the job number of the currently active job.
Lprm will remove a job, or jobs, from a printer's spool queue. -G, --no-group Inhibit display of group information
--indicator-style=WORD Append indicator with style WORD to entry names: -U do not sort; list entries in directory order
none (default), classify (-F), file-type (-p)
-v sort by version
-i, --inode Print index number of each file
-w, --width=COLS assume screen width instead of current value
-I, --ignore=PATTERN Do not list implied entries matching shell PATTERN
-x list entries by lines instead of by columns
-k, --kilobytes Like --block-size=1024
-X sort alphabetically by entry extension
-l Use a long listing format
-1 list one file per line
-L, --dereference List entries pointed to by symbolic links
--help display help and exit
-m Fill width with a comma separated list of entries
--version output version information and exit
-n, --numeric-uid-gid List numeric UIDs and GIDs instead of names The most common options are -a (all files) and -l (long or details)
-N, --literal Print raw entry names (don't treat e.g. control
characters specially) When output to file the files are listed one per line.
-o Use long listing format without group info By default, colour is not used to distinguish types of files. That is equivalent to using --
-p, --file-type Append indicator (one of /=@|) to entries color=none.
Using the --color option without the optional WHEN argument is equivalent to using --
-q, --hide-control-chars Print ? instead of non graphic characters color=always.
With --color=auto, color codes are output only if standard output is connected to a terminal (tty).
--show-control-chars Show non graphic characters as-is (default)
Examples
-Q, --quote-name Enclose entry names in double quotes # List the contents of your home directory
--quoting-style=WORD Use quoting style WORD for entry names: $ ls ~
literal, shell, shell-always, c, escape
# list everything in a vertical list:
-r, --reverse Reverse order while sorting $ ls -al
mknod -p Do not scroll. Instead, clear the whole screen and then display
the text.
creates a FIFO, character special file, or block special file with the specified name. -c Do not scroll. Instead, paint each screen from the top, clearing
Syntax the remainder of each line as it is displayed.
mknod [options]... NAME Type [Major Minor]
-s Squeeze multiple blank lines into one.
Options
-u Suppress underlining.
-m MODE
--mode=MODE +/ The +/ option specifies a string that will be searched for before
Set the mode of created files to MODE, which is symbolic as in each file is displayed.
`chmod' and uses 0666 minus the bits set in the umask as the point
of departure. +num Start at line number num.
Type The type of file to make: COMMANDS
`p' for a FIFO Interactive commands for more are based on vi(1). Some commands may be
`b' for a block special file preceeded by a decimal number, called k in the descriptions below. In
`c' for a character special file the following descriptions, ^X means control-X.
Major/Minor When making a block or character special file, the major and minor h or ? Help: display a summary of these commands. If you forget all
device numbers must be given after the file type. the other commands, remember this one.
Unlike the phrase "special file type" above, the term "special file" has a technical meaning on
Unix: something that can generate or receive data. Usually this corresponds to a physical piece of SPACE Display next k lines of text. Defaults to current screen
hardware, e.g., a printer or a disk. (These files are typically created at system-configuration time.) size.
The `mknod' command is what creates files of this type. Such devices can be read either a z Display next k lines of text. Defaults to current screen
character at a time or a "block" (many characters) at a time, hence we say there are "block size. Argument becomes new default.
special" files and "character special" files.
RETURN Display next k lines of text. Defaults to 1.
more Argument becomes new default.
Display output one screen at a time, less provides more emulation and extensive enhancements. d or ^D Scroll k lines. Default is current scroll size, initially
SYNTAX 11. Argument becomes new default.
more [-dlfpcsu] [-num] [+/ pattern] [+ linenum] [file ...]
q or Q or INTERRUPT Exits the more command.
OPTIONS
Command line options are described below. Options are also taken from s Skip forward k lines of text. Defaults to 1.
the environment variable MORE (make sure to precede them with a dash
(``-'')) but command line options will override them. f Skip forward k screenfuls of text. Defaults to 1.
-num This option specifies an integer which is the screen size (in b or ^B Skip backwards k screenfuls of text. Defaults to 1.
lines).
' Go to place where previous search started.
-d more will prompt the user with the message "[Press space to continue,
:n Go to kth next file. Defaults to 1. -s Tolerate sloppy mount options rather than failing.
This option exists for support of the Linux
:p Go to kth previous file. Defaults to 1. autofs-based automounter.
:f Display current file name and line number -r Mount the file system read-only. A synonym is -o ro
. Repeat previous command -w Mount the file system read/write. This is the
default. A synonym is -o rw.
ENVIRONMENT
More utilizes the following environment variables, if they exist: -L label
Mount the partition that has the specified label.
MORE This variable may be set with favored options to more.
SHELL Current shell in use (normally set by the shell at login -U uuid
Mount the partition that has the specified uuid.
mount -o Several -o options can be specified in a comma separated
mount a file system string ... see info for more
All files accessible in a Unix system are arranged in one big tree, the file hierarchy, rooted at /.
These files can be spread out over several devices. The mount command serves to attach the file async All I/O to the file system should be done
asynchronously.
system found on some device to the big file tree.
SYNTAX atime Update inode access time for each access.
mount -a [-fFnrsvw] [-t vfstype] This is the default.
mount [-fnrsvw] [-o options [,...]] device | dir noatime
Do not update inode access times on this
mount [-fnrsvw] [-t vfstype] [-o options] device dir file system (e.g, for faster access on the
news spool to speed up news servers).
mount [-hV]
OPTIONS auto Can be mounted with the -a option.
-a Mount all filesystems (of the given types) mentioned noauto Can only be mounted explicitly (i.e., the -a
in fstab. option will not cause the file system to be
mounted).
-F (Used in conjunction with -a.) Fork off a new
incarnation of mount for each device. This will do ro Mount the file system read-only.
the mounts on different devices or different NFS
servers in parallel. This has the advantage that rw Mount the file system read-write.
it is faster; also NFS timeouts go in parallel. A
disadvantage is that the mounts are done in unde- suid Allow set-user-identifier or set-group-identifier bits to
fined order. Thus, you cannot use this option if take effect.
you want to mount both /usr and /usr/spool.
-t vfstype
Mtools are typically used to manipulate FAT formatted floppy disks. Each program attempts to
The argument following the -t is used to indicate emulate the MS-DOS equivalent command, these are different from Windows NT/2000
the file system type. commands.
-h Print a help message.
Mtools is sufficient to give access to MS-DOS filesystems. For instance, commands such as `mdir
-V Output version. a:' work on the `a:' floppy without any preliminary mounting or initialization (assuming the
default `/etc/mtools.conf' works on your machine). With mtools, one can change floppies too
-v Verbose mode. without unmounting and mounting.
MTOOLS Programs
File system specific MOUNT options
see info mount for these floppyd floppy daemon to run on your X server box
The standard form of the mount command, is mount -t type device dir This tells the kernel to floppyd_installtest small utility to check for the presence of floppyd
attach the file system found on device (which is of type type) at the directory dir. The previous mattrib change MS-DOS file attribute flags
contents (if any) and owner and mode of dir become invisible, and as long as this file system mbadblocks tests a floppy disk, and marks the bad blocks in the FAT
mcat same as cat. Only useful with floppyd.
remains mounted, the pathname dir refers to the root of the file system on device. mcd change MS-DOS directory
mcopy copy MS-DOS files to/from Unix
Three forms of invocation do not actually mount anything: mdel delete an MS-DOS file
mdeltree recursively delete an MS-DOS directory
mdir display an MS-DOS directory
print a help message: mdu list space occupied by directory and its contents
mount -h mformat add an MS-DOS filesystem to a low-level formatted floppy disk
minfo get information about an MS-DOS filesystem.
mlabel make an MS-DOS volume label
print a version string: mkmanifest makes a list of short name equivalents
mount -V mmd make an MS-DOS subdirectory
mmount mount an MS-DOS disk
list all mounted file systems of type 'type' mpartition create an MS-DOS as a partition
mrd remove an MS-DOS subdirectory
mount [-t type] mmove move or rename an MS-DOS file or subdirectory
mren rename an existing MS-DOS file
The proc file system is not associated with a special device, and when mounting it, an arbitrary mshowfat shows the FAT map of a file
keyword, such as proc can be used instead of a device specification. (The customary choice none mtoolstest tests and displays the configuration
mtype display contents of an MS-DOS file
is less fortunate: the error message `none busy' from umount can be confusing.) mzip zip disk specific commands
xcopy recursively copy a dos directory into another
Most devices are indicated by a file name (of a block special device), like /dev/sda1, but there are Equivalent Windows commands:
other possibilities. For example, in the case of an NFS mount, device may look like
knuth.cwi.nl:/dir. It is possible to indicate a block special device using its volume label or UUID mtr
(see the -L and -U options below). Network diagnostics (traceroute/ping.)
Syntax
mtr [-hvrctglspni46] [--help] [--version] [--report] [--report-cycles COUNT]
The file /etc/fstab (see fstab), may contain lines describing what devices are usually mounted [--curses] [--split] [--raw] [--no-dns] [--gtk] [--address
where, using which options. IP.ADD.RE.SS]
[--interval SECONDS] [--psize BYTES | -s BYTES]
mtools HOSTNAME [PACKETSIZE]
Mtools is a public domain collection of tools to allow Unix systems to manipulate MS-DOS files: Key
read, write, and move around files on an MS-DOS filesystem -c COUNT
-S SUFFIX -d Delete
--suffix=SUFFIX -p Protect (don't delete or overwrite)
Append SUFFIX to each backup file made with `-b'. -g Go
The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX. -t Terminate
-v verbose mode
-u -n no-execute mode (display messages about what would have been done)
--update
Do not move a nondirectory that has an existing destination with Source_Options:
the same or newer modification time.
-m Move source file to target name.
-v Both must be on the same device. Will not move directories.
--verbose If the source file is a symbolic link, moves the link without checking
Print the name of each file before moving it. if the link's target from the new directory is different than the old.
-V METHOD -x same as -m, except cross-device moves are done by copying, then deleting
--version-control=METHOD' source.
Change the type of backups made with `-b'. METHOD can be: When copying, sets the permission bits and file modification time of the
target
t, numbered make numbered backups file to that of the source file.
nil, existing numbered if numbered backups exist, simple otherwise
never, simple always make simple backups -r Rename source file or directory to target name.
The target name must not include a path: the file remains in the same
--help display help and exit directory
--version output version information and exit in all cases. This option is the only way of renaming directories under
mmv.
Examples
-c Copy source file to target name.
Rename the file apple as orange.doc: Sets the file modification time and permission bits of the target file to
mv apple orange.doc that
of the source file, regardless of whether the target file already exists.
Move orange.doc to the Documents folder: Chains and cycles (to be explained below) are not allowed.
mv orange.doc ~/Documents/orange.doc
-o Overwrite target name with source file.
Rename a bunch of file extensions If target file exists, it is overwritten, keeping its original owner and
e.g. change *.txt into *.htm permission bits. If it does not exist, it is created, with read-write
for f in *.txt; do mv ./"$f" "${f%txt}htm"; done permission
bits set according to umask, and the execute permission bits copied from
`mv' can move only regular files across filesystems. the
source file. In either case, the file modification time is set to the
If a destination file exists but is normally unwritable, standard input is a terminal, and the `-f' or `- current time.
Multiple from -- to pattern pairs may be specified by omitting the pattern pair on the command Files beginning with ’.’ are only matched against from patterns that begin with an explicit ’.’.
line, and entering them on the standard input, one pair per line. (If a pattern pair is given on the However, if -h is specified, they are matched normally.
command line, the standard input is not read.) Thus,
Warning: since the shell normally expands wildcards before passing the command-line arguments
mmv to mmv, it is usually necessary to enclose the command-line from and to patterns in quotes.
ab
Bash programming for linux | nubielab.com 97
Mmv detects chains and cycles regardless of the order in which their constituent actions are
The To Pattern actually given. Where allowed, i.e. in moving, renaming, and appending files, chains and cycles
are handled gracefully, by performing them in the proper order. Cycles are broken by first
The to pattern is a filename with embedded wildcard indexes, where an index consists of the renaming one of the files to a temporary name (or just remembering its original size when doing
character ’#’ followed by a string of digits. appends).
When a source file matches a from pattern, a target name for the file is constructed out of the to
pattern by replacing the wildcard indexes by the actual characters that matched the referenced Collisions and Deletions
wildcards in the source name. Thus, if the from pattern is "abc*.*" and the to pattern is
"xyz#2.#1", then "abc.txt" is targeted to "xyztxt.". (The first ’*’ matched "", and the second When any two or more matching files would have to be moved, copied, or linked to the same
matched "txt".) Similarly, for the pattern pair ";*.[clp]" -> "#1#3/#2", "foo1/foo2/prog.c" is target filename, mmv detects the condition as an error before performing any actions.
targeted to "foo1/foo2/c/prog". Note that there is no ’/’ following the "#1" in the to pattern, since Furthermore, mmv checks if any of its actions will result in the destruction of existing files.
the string matched by any ’;’ is always either empty or ends in a ’/’. In this case, it matches If the -d (delete) option is specified, all file deletions or overwrites are done silently.
"foo1/foo2/". Under -p (protect), all deletions or overwrites (except those specified with "(*)" on the standard
input, see below) are treated as errors. And if neither option is specified, the user is queried about
To convert the string matched by a wildcard to either lowercase or uppercase before embedding it each deletion or overwrite separately. (A new stream to "/dev/tty" is used for all interactive
in the target name, insert ’l’ or ’u’, respectively, between the ’#’ and the string of digits. queries, not the standard input.)
The to pattern, like the from pattern, can begin with a "~/" (see above). This does not necessitate Error Handling
enclosing the to pattern in quotes on the command line since csh(1) expands the ’~’ in the exact
same manner as mmv (or, in the case of sh(1), does not expand it at all). Whenever any error in the user’s action specifications is detected, an error message is given on
the standard output, and mmv proceeds to check the rest of the specified actions. Once all errors
For all task options other than -r, if the target name is a directory, the real target name is formed are detected, mmv queries the user whether he wishes to continue by avoiding the erroneous
by appending a ’/’ followed by the last component of the source file name. For example, "mmv actions or to abort altogether. This and all other queries may be avoided by specifying either the -
dir1/a dir2" will, if "dir2" is indeed a directory, actually move "dir1/a" to "dir2/a". However, if g (go) or -t (terminate)
"dir2/a" already exists and is itself a directory, this is considered an error. option. The former will resolve all difficulties by avoiding the erroneous actions; the latter will
abort mmv if any errors are detected.
To strip any character (e.g. ’*’, ’?’, or ’#’) of its special meaning to mmv, as when the actual Specifying either of them defaults mmv to -p, unless -d is specified (see above). Thus, -g and -t
replacement name must contain the character ’#’, precede the special character with a ´\’ (and are most useful when running mmv in the background or in a shell script, when interactive
enclose the argument in quotes because of the shell). This also works to terminate a wildcard queries are undesirable.
index when it has to be followed by a digit in the filename, e.g. "a#1\1".
Reports
Chains and Cycles
Once the actions to be performed are determined, mmv performs them silently, unless either the -
A chain is a sequence of specified actions where the target name of one action refers to the source v (verbose) or -n (no-execute) option is specified. The former causes mmv to report each
file of another action. For example, performed action on the standard output as
Under -n, none of the actions are performed, but messages like the above are printed on the nice
standard output with the ": done." omitted. Run a command with modified scheduling priority, print or modify the scheduling priority of a
job.
SYNTAX
The output generated by -n can (after editing, if desired) be fed back to mmv on the standard nice [Option]... [Command [Arg]...]
input (by omitting the from -- to pair on the mmv command line). To facilitate this, mmv ignores
lines on the standard input that look like its own error and "done" messages, as well as all lines OPTION
beginning with white space, and will accept pattern pairs -n MyADJUSTMENT
-MyADJUSTMENT
with or without the intervening "->" (or "-^", "=>", or "=^"). Lines with "(*)" after the target --adjustment=MyADJUSTMENT
pattern have the effect of enabling -d for the files matching this pattern only, so that such
deletions are done silently. When feeding mmv its own output, one must remember to specify Priority can be adjusted by `nice' over the range
again the task option (if any) originally used to generate it. of -20 (the highest priority)
to 19 (the lowest)
If no arguments are given, `nice' prints the current scheduling priority, which it inherited.
Although mmv attempts to predict all mishaps prior to performing any specified actions,
Otherwise, `nice' runs the given Command with its scheduling priority adjusted.
accidents may happen. For example, mmv does not check for adequate free space when copying.
Thus, despite all efforts, it is still possible for an action to fail after some others have already been
If no option for MyADJUSTMENT is given, the priority of the command is incremented by 10.
done. To make recovery as easy as possible, mmv reports which actions have already been done
You must have appropriate privileges to specify a negative adjustment.
and which are still to be performed after such a failure occurs. It then aborts, not attempting to do
anything else. Once the user has cleared up the problem, he can feed this report back to mmv on
Because most shells have a built-in command by the same name, using the unadorned command
the standard input to have it complete the task. (The user is queried for a file name to dump this
name in a script or interactively may get you different functionality than that described here.
report if the standard output has not been redirected.)
Mmv exits with status 1 if it aborts before doing anything, with status 2 if it aborts due to failure
after completing some of the actions, and with status 0 otherwise.
nl
Number lines and write files, writes each FILE to standard output, with line numbers added to
Example
some or all of the lines.
BUGS If no input file (or `-' ) is given nl will read from standard input.
If the search pattern is not quoted, the shell expands the wildcards. Mmv then (usually) gives SYNTAX
some error message, but can not determine that the lack of quotes is the cause. nl [options]... [File]...
OPTIONS
To avoid difficulties in semantics and error checking, mmv refuses to move or create directories.
If the mmv tool is not installed on your distro, get it with: apt-get install mmv `-b STYLE'
Examples `--body-numbering=STYLE'
Rename the file extension of all .csv files in the current directory to .xls Select the numbering style for lines in the body section of each
logical page. When a line is not numbered, the current line number
mmv "*.csv" "#1.xls" is not incremented, but the line number separator character is
Copy report6part4.txt to ./french/rapport6partie4.txt along with all similarly named files: still prepended to the line.
mmv -c "report*part*.txt" "./french/rapport#1partie#2.txt" The styles are:
Append the contents of all .txt files into one file:
`a' number all lines,
mmv -a "*.txt" "all.txt"
`t' number only nonempty lines (default for body),
netstat `n' do not number lines (default for header and footer),
Networking information `pREGEXP' number only lines that contain a match for REGEXP.
`-f STYLE' `nl' treats all of the input files as a single document; it does not reset line numbers or logical pages
`--footer-numbering=STYLE' between files.
Analogous to `--body-numbering'.
`-h STYLE' A logical page consists of three sections: header, body, and footer. Any of the sections can be
`--header-numbering=STYLE' empty. Each can be numbered in a different style from the others.
Analogous to `--body-numbering'.
`-i NUMBER' The beginnings of the sections of logical pages are indicated in the input file by a line containing
`--page-increment=NUMBER' exactly one of these delimiter strings:
Increment line numbers by NUMBER (default 1). `\:\:\:' start of header;
`-l NUMBER'
`\:\:' start of body;
`--join-blank-lines=NUMBER' `\:' start of footer.
Consider NUMBER (default 1) consecutive empty lines to be one The two characters from which these strings are made can be changed from `\' and `:' via options
logical line for numbering, and only number the last one. Where (see above), but the pattern and length of each string cannot be changed. A section delimiter is
fewer than NUMBER consecutive empty lines occur, do not number
them. An empty line is one that contains no characters, not even
replaced by an empty line on output.
spaces or tabs.
Any text that comes before the first section delimiter string in the input file is considered to be
`-n FORMAT' part of a body section, so `nl' treats a file that contains no section delimiters as a single body
`--number-format=FORMAT'
Select the line numbering format (default is `rn'): section.
`ln'
left justified, no leading zeros;
nohup
No Hang Up. Run a command immune to hangups, runs the given command with hangup signals
`rn' ignored, so that the command can continue running in the background after you log out.
right justified, no leading zeros; SYNTAX
nohup Command [Arg]...
`rz' `nohup' increases the scheduling priority of COMMAND by 5, this gives a slightly lower priority.
right justified, leading zeros.
`-p'
If standard output is a terminal, it and standard error are redirected so that they are appended to
`--no-renumber' the file `nohup.out'; if that cannot be written to, they are appended to the file
Do not reset the line number at the start of a logical page. `$HOME/nohup.out'. If that cannot be written to, the command is not run.
`-s STRING'
`--number-separator=STRING' If `nohup' creates either `nohup.out' or `$HOME/nohup.out', it creates it with no "group" or
Separate the line number from the text line in the output with "other" access permissions. It does not change the permissions if the output file already existed.
STRING (default is the TAB character).
`nohup' does not automatically put the command it runs in the background; you must do that
`-v NUMBER'
`--starting-line-number=NUMBER' explicitly, by ending the command line with an `&'.
Set the initial line number on each logical page to NUMBER
(default 1). notify-send
Bash programming for linux | nubielab.com 100
A program to send desktop notifications, inform the user about an event or display some form of Look up information for host using the current default server or using
server,
information without getting in the user’s way. if specified. If host is an Internet address and the query type is A or
Syntax
PTR ,
notify-send [OPTIONS] [body]
the name of the host is returned. If host is a name and does not have a
trailing
Key
period, the default domain name is appended to the name. (This behavior
-u, --urgency=LEVEL
depends
The urgency level (low, normal, critical).
on the state of the set options domain , srchlist , defname , and
search.
-t, --expire-time=TIME
The timeout in milliseconds at which to expire the
To look up a host not in the current domain, append a period to the
notification.
name.
-i, --icon=ICON[,ICON...]
server domain
An icon filename or stock icon to display.
lserver domain
Change the default server to domain ; lserver uses the initial server to
-c, --category=TYPE[,TYPE...]
look up
Specifies the notification category.
information about domain while server uses the current default server.
If an authoritative answer can't be found, the names of servers that
-?, --help
might have
Show a help message
the answer are returned.
root
-h, --hint=TYPE:NAME:VALUE
Change the default server to the server for the root of the domain name
Pass extra data. Valid TYPEs are int, double, string and byte.
space.
Currently, the host ns.internic.net is used. (This command is a synonym
To use notify-send, you may need to install the following package: for
$ sudo apt-get install libnotify-bin `lserver ns.internic.net' The name of the root server can be changed
Examples with
the `set root ' command.
$ notify-send "Hello World"
$ notify-send -t 5000 -u low "Hello World" finger [name ] [> filename ]
The return status is zero if all information was written successfully. finger [name ] [>> filename ]
Connects with the finger server on the current host. The current host
nslookup is
defined when a previous lookup for a host was successful and returned
Query Internet name servers address
Syntax: information (see the `set querytype=A ' command). The name is optional.
nslookup > and
>> can be used to redirect output in the usual manner.
nslookup host-to-find
ls [option ] domain [> filename ]
nslookup server ls [option ] domain [>> filename ]
List the information available for domain , optionally creating or
interactive mode: appending
to filename The default output contains host names and their Internet
nslookup -server addresses.
Option can be one of the following:
nslookup [-options] [host-to-find ]
-t querytype list all records of the specified type (see querytype
Options: below).
-a list aliases of hosts in the domain; synonym for `-t
host [server ] CNAME '
-d list all records for the domain; synonym for `-t ANY'
When output is directed to a file, hash marks are printed for every 50 -l List available commands.
records Note that this will only display commands you are permitted to run.
received from the server. Configuration
view filename
Configuration entries are read from /etc/op.conf and all files in lexical order from /etc/op.d with
Sort and lists the output of previous ls command(s) with more(1). the extension .conf. Files must be owned by root and not have group or other permissions set.
The fields of the entries in the configuration files are separated by white space. Each entry may
set keyword [= value ] span several lines and continues until the next alphanumeric string is found at the beginning of a
This command is used to change state information that affects the
lookups. lines (which is taken to be the next mnemonic or variable definition, and thus the beginning of a
run man nslookup for a full list of valid keywords. new entry). Comments may be embedded beginning with a # character. Each entry in the
configuration files has the following form:
set all Print the current value of the frequently-used options mnemonic
to set Information about the current default server and host is also
printed. command [ arg ... ] ; [ option ... ]
or
help var=value
? Print a brief summary of commands.
Key:
exit Exit the program. var a variable name, which must be an upper case alphanumeric identifier. Variables are
Nslookup has two modes: interactive and non-interactive. expanded when reading options.
Interactive mode allows the user to query name servers for information about various hosts and value the remainder of the line is taken to be the value of the variable.
domains or to print a list of hosts in a domain. mnemonic a unique, alphanumeric identifier for each operator function.
Non-interactive mode is used to print just the name and requested information for a host or command the full pathname of the executable to be run by op when the associated mnemonic is
domain. chosen.
The options listed under the `set ' command can be specified in the .nslookuprc file in the user's arg(s) any arguments, either literal or variable, needed by command. Literal arguments are simply
home directory (listed one per line). Options can also be specified on the command line if they specified directly, like specific command options (0Gun) or files (/dev/rmt20). Variable
precede the arguments and are prefixed with a hyphen. arguments are specified here as $1, $2 ... $n;
For a full list look in the options section of the op man page( man op ).
open $* indicates any number trailing arguments.
Open a file in its default application, using virtual terminal (VT). Examples
Syntax Example /etc/op.conf:
open Files... # Define some users
Options:
OPERATORS=(fred|barry)
files The filename(s) to open, wildcards are accepted. # Define hosts that Fred is restricted to
Example FRED_HOSTS=(alpha|beta)
Open all the text files in the current directory using your default text editor: # Define hosts that Barry is restricted to
open *.txt BARRY_HOSTS=(theta|gamma)
# Define user/host access list
op ACCESS_LIST=fred@FRED_HOSTS|barry@BARRY_HOSTS
Operator access. A flexible means for system administrators to grant trusted users access to # 'op shell' - gives user a root shell
certain root operations without having to give them full superuser privileges. shell
Syntax
-k, --keep-tokens keep non-expired authentication tokens -A Adaptive ping. Interpacket interval adapts to round-trip time,
so that effectively not more than one (or more, if preload is set)
-l, --lock lock the named account (root only) unanswered probes
-F flow_label Allocate and set 20 bit flow label on echo request packets. -s packetsize
(Only ping6). The number of data bytes to be sent. The default is 56, which
If value is zero, kernel allocates random flow label. translates into
64 ICMP data bytes when combined with the 8 bytes of ICMP header
-f Flood ping, output packets as fast as they come back or 100 times data.
per second.
-S sndbuf Set socket sndbuf. If not specified, it is selected to buffer not
-i wait Set an interval of wait seconds between sending each packet. more than one packet.
default=one second.
Only super-user may set wait to values less 0.2 seconds. -t ttl Set the IP Time to Live.
(incompatible with -f)
-T timestamp_option
-I interface address Set special IP timestamp options, either 'tsonly' (only
Set source address to specified interface_address. timestamps),
Argument may be numeric IP address or name of device. 'tsandaddr' (timestamps and addresses)
Required when pinging an IPv6 link-local address. or 'tsprespec host1 [host2 [host3 [host4]]]' (timestamp
prespecified hops).
-l preload If preload is specified, ping sends that many packets as fast as
possible before falling into its normal mode of behavior. -M hint Select Path MTU Discovery strategy. hint may be either 'do'
Only the super-user may select preload more than 3. (prohibit fragmentation,
even local one), 'want' (do PMTU discovery, fragment locally when
-L Suppress loopback of multicast packets. packet size is large),
only applies if the ping destination is a multicast address. or 'dont' (do not set DF flag).
-n Numeric output only. No attempt will be made to lookup symbolic -U Print full user-to-user latency (the old behaviour).
names for host addresses. Normally ping prints network round trip time, which can be
-p pattern different f.e. due to DNS failures.
Specify up to 16 `pad' bytes to fill out the packet sent.
This is useful for diagnosing data-dependent problems in a -v Verbose output. ICMP packets other than ECHO_RESPONSE that are
network. eg, `-p ff' will fill the packet sent with all ones. received are listed.
-q Quiet output. Only display the summary lines at startup time and Ping is intended for use in network testing, measurement and management. Because of the load it
when finished.
can impose on the network, it is unwise to use ping during normal operations or from automated
-Q tos Set Quality of Service -related bits in ICMP datagrams. tos can be scripts.
a decimal or hex number. If ping does not receive any reply packets at all it will exit with code 1. If a packet count and
Multiple TOS bits should not be set simultaneously. For detail see deadline are both specified, and fewer than count packets are received by the time the deadline
RFC1349 and RFC2474
has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits
with code 0. This makes it possible to use the exit code to see if a host is alive or not.
-v
Either the numerical or symbolical value may be used.
pr
Negates the matching. Prepare files for printing, printing and pagination filter for text files.
-x When multiple input files are specified, each is read, formatted, and written to standard output.
Only match processes whose name (or command line if -f is specified) SYNTAX
exactly match the pattern. pr [options] [file ...]
-signal
Defines the signal to send to each matched process. OPTIONS
Either the numeric or the symbolic signal name can be used. (pkill only.)
All the criteria have to match. +beg_pag[:end-pag],
For example, pgrep -u root sshd will only list the processes called sshd AND owned by root. --pages=[beg_pag[:end-pag]
On the other hand, pgrep -u root,daemon will list the processes owned by root OR daemon. Begin printing on page beg_pag and end on end-pag if specified.
Examples -num_cols
Example 1: Find the process ID of the named daemon: --columns=num_cols
$ pgrep -u root named Print in num_cols number of columns, balancing the number of lines
Example 2: Make syslog reread its configuration file: in the columns on each page.
$ pkill -HUP syslogd -a
Example 3: Give detailed information on all xterm processes: --across
$ ps -fp $(pgrep -d, -x xterm) Print columns horizontally, not vertically.
Example 4: Make all netscape processes run nicer: -c
$ renice +4 'pgrep netscape' --show-control-chars
Exit Status Convert control characters to hat notation (such as ^C) and other
1. One or more processes matched the criteria. unprintable characters to octal backslash format.
-d
2. No processes matched. --double-space
3. Syntax error in the command line. Double space.
4. Fatal error: out of memory etc.
-e[tab-char[width]]
popd --expand-tabs=[tab-char[width]]
Convert tabs (or tab-chars) to spaces.
Remove the top entry from the directory stack, and cd to the new top directory. If width is specified, convert tabs to width characters (default is 8).
SYNTAX
popd [+N | -N] [-n] -f
-F
Key --form-feed
+N Remove the Nth directory (counting from the left of the list Separate pages with form feeds, not newlines.
printed by dirs), starting with zero.
-h header
-l lines file
--length=lines A pathname of a file to be printed.
Set page length to lines (default 66). If lines is less than 10, omit If no file operands are specified, or if a file operand is `-',
headers and footers. the standard input is used.
-m --help
--merge Print a help message and then exit.
Print all files, one file per column.
--version
-n[delimiter[digits]] Print version information and then exit.
--number-lines[=delimiter[digits]]
Number columns, or, with the -m option, number lines.
Append delimiter to each number (default is a tab) and limit
printf
the size of numbers to digits (default is 5). Format and print data.
Write the formatted arguments to the standard output under the control of the format.
-o width SYNTAX
--indent=width printf format [argument]...
Set left margin to width.
printf --help
-r
--no-file-warnings printf --version
Continue silently when unable to open an input file.
OPTIONS
-s[delimiter]
--separator[=delimiter] The format characters and their meanings are:
Separate columns with delimiter (default is a tab) instead of spaces.
\" double quote
-S[string]
--sep-string[=string] \0NNN character with octal value NNN (0 to 3 digits)
Separate columns with string. Default is a tab with -J and a space
otherwise. \\ backslash
-t \a alert (BEL)
--omit-header
Suppress headers, footers, and fills at end of pages. \b backspace
-v \n new line
--show-non-printing
\UNNNNNNNN
character with hexadecimal value NNNNNNNN (8 digits)
ps
Process status, information about processes running in memory. If you want a repetitive update of
%% a single % this status, use top.
Syntax
%b ARGUMENT as a string with `\' escapes interpreted
ps option(s)
%Wd Integer `W' digits wide xxxx ps [-L]
Output Modifiers: The "h" option varies between BSD personality and Linux usage (not printing the header)
C use raw CPU time for %CPU instead of decaying average Regardless of the current personality, you can use the long options --headers and --no-headers
c true command name
e show environment after the command
f ASCII-art process hierarchy (forest)
Terminals (ttys, or screens of text output) can be specified in several forms: /dev/ttyS1, ttyS1, S1.
-H show process hierarchy (forest) Obsolete "ps t" (your own terminal) and "ps t?" (processes without a terminal) syntax is
h do not print header lines (repeat header lines in BSD supported, but modern options ("T","-t" with list, "x", "t" with list) should be used instead.
personality)
-m m show all threads
-n set namelist file
The BSD "O" option can act like "-O" (user-defined output format with some common fields
n numeric output for WCHAN and USER predefined) or can be used to specify sort order. Heuristics are used to determine the behavior of
N specify namelist file this option. To ensure that the desired behavior is obtained, specify the other option (sorting or
O sorting order (overloaded) formatting) in some other way.
S include some dead child process data (as a sum with the
parent)
-w w wide output For sorting, BSD "O" option syntax is O[+|-]k1[,[+|-]k2[,...]] Order the process listing according
--cols set screen width to the multilevel sort specified by the sequence of short keys from SORT KEYS, k1, k2, ... The
--columns set screen width `+' is quite optional, merely re-iterating the default direction on a key. `-' reverses direction only
--forest ASCII art process tree
--html HTML escaped output on the key it precedes.
--headers repeat header lines The O option must be the last option in a single command argument, but specifications in
Bash programming for linux | nubielab.com 109
successive arguments are catenated. D uninterruptible sleep (usually IO)
R runnable (on run queue)
S sleeping
GNU sorting syntax is --sortX[+|-]key[,[+|-]key[,...]] T traced or stopped
Choose a multi-letter key from the SORT KEYS section. X may be any convenient separator Z a defunct ("zombie") process
character. To be GNU-ish use `='. The `+' is really optional since default direction is increasing
For BSD formats and when the "stat" keyword is used,
numerical or lexicographic order. For example, ps jax --sort=uid,-ppid,+pid additional letters may be displayed:
W has no resident pages
This ps works by reading the virtual files in /proc. This ps does not need to be suid kmem or have < high-priority process
any privileges to run. Do not give this ps any special permissions. N low-priority task
L has pages locked into memory (for real-time and custom IO)
This ps needs access to a namelist file for proper WCHAN display. The namelist file must match ENVIRONMENT VARIABLES and PERSONALITY (posix,linux,bsd,sun)
the current Linux kernel exactly for correct output. Examples:
List every process on the system using standard syntax:
To produce the WCHAN field, ps needs to read the System.map file created when the kernel is ps -e
compiled. The search path is:
$PS_SYSTEM_MAP List every process on the system using BSD syntax:
/boot/System.map-`uname -r`
/boot/System.map
ps ax
/lib/modules/`uname -r`/System.map List the top 10 CPU users.
/usr/src/linux/System.map ps -e -o pcpu -o pid -o user -o args | sort -k 1 | tail -21r
/System.map
The member used_math of task_struct is not shown, since crt0.s checks to see if math is present. List every process except those running as root (real & effective ID)
This causes the math flag to be set for all processes, and so it is Programs swapped out to disk ps -U root -u root -N
will be shown without command line arguments, and unless the c option is given, in brackets.
List every process with a user-defined format:
%CPU shows the cputime/realtime percentage. It will not add up to 100% unless you are lucky. It ps -eo pid,tt,user,fname,tmout,f,wchan
is time used divided by the time the process has been running.
Odd display with AIX field descriptors:
The SIZE and RSS fields don't count the page tables and the task_struct of a proc; this is at least ps -o "%u : %U : %p : %a"
12k of memory that is always resident. SIZE is the virtual size of the proc (code+data+stack).
Print only the process IDs of syslogd:
Processes marked defunct are dead processes (so-called"zombies") that remain because their ps -C syslogd -o pid=
parent has not destroyed them properly. These processes will be destroyed by init(8) if the parent When displaying multiple fields, part of the output may be truncated, to avoid this supply a width
process exits. to the arguments:
PROCESS FLAGS ps -e -o user:20,args.
ALIGNWARN 001 print alignment warning msgs
STARTING 002 being created Since ps cannot run faster than the system and is run as any other scheduled process, the
EXITING 004 getting shut down information it displays can never be exact.
PTRACED 010 set if ptrace (0) has been called
TRACESYS
FORKNOEXEC
020
040
tracing system calls
forked but didn't exec
pushd
SUPERPRIV 100 used super-user privileges Save and then change the current directory. With no arguments, pushd exchanges the top two
DUMPCORE 200 dumped core directories.
SIGNALED 400 killed by a signal SYNTAX
pushd [dir | +N | -N] [-n]
PROCESS STATE CODES KEY
-n Suppresses the normal change of directory when adding directories to the Files
stack, so that only the stack is manipulated. quota.user located at the filesystem root with user quotas
quota.group located at the filesystem root with group quotas
dir Makes the current working directory be the top of the stack, and then
executes /etc/fstab to find filesystem names and locations
the equivalent of `cd dir'. cds to dir.
quotacheck
pwd Scan a file system for disk usage
Print Working Directory (shell builtin) Syntax
Syntax quotacheck [-g] [-u] [-v] -a
pwd [-LP] quotacheck [-g] [-u] [-v] filesys ...
Quotacheck performs a filesystems scan for usage of files and directories, used by either user or
Options group. The output is the quota file for the corresponding filesystem. By default the names for
-P : The pathname printed will not contain symbolic links.
-L : The pathname printed may contain symbolic links
these files are:
The default action is to show the current folder as an absolute path. - A user scan: quota.user
All components of the path will be actual folder names - none will be symbolic links. - A group scan: quota.group
quota The resulting file consist of a struct dqblk for each possible id up to the highest existing uid or gid
and contains the values for the disk file and block usage and possibly excess time for these
Display disk usage and limits, by default only the user quotas are printed.
SYNTAX values. ( for definitions of struct dqblk see )
quota [ -guv | q ]
quota [ -uv | q ] user Quotacheck should be run each time the system boots and mounts non-valid file systems. This is
quota [ -gv | q ] group
most likely to happen after a system crash.
OPTIONS
-g Print group quotas for the group of which the user The speed of the scan is proportional to the number of directories/files.
is a member. OPTIONS
-v This way the program will give some useful information
-u Print user quotas (this is the default) about what it is doing, plus some fancy
stuff.
-v Verbose, will display quotas on filesystems where no
storage is allocated. -d This means debug. It will result in a lot of information
which can be used in debugging the program.
-q Print a more terse message, containing only information The output is very verbose and the scan will not be
on filesystems where usage is over quota. fast.
Specifying both -g and -u displays both the user quotas and the group quotas (for the user).
-u This flag tells the program to scan the disk and to
count the files and directories used by a certain
Only the super-user may use the -u flag and the optional user argument to view the limits of other uid. This is the default action.
users. Non- super-users can use the the -g flag and optional group argument to view only the
limits of groups of which they are members. -g This flag forces the program to count the the files
and directories used by a certain gid.
-R When used in conjunction with -a, all filesystems Q_SYNC Update the on-disk copy of quota usages for
except the root filesystem are checked for quotas. a file system. If special is null then all
NOTE Quotacheck should only be run as Super User. Non-priviliged users are presumably not file systems with active quotas are
sync'ed. addr and uid are ignored.
allowed to read all the directories on the given file system.
RETURN VALUES
quotactl
Set disk quotas 0 on success.
SYNTAX
#include <linux/quota.h> -1 on failure and sets errno to indicate the error.
-a aname If no names are supplied, the line read is assigned to the variable REPLY. The return code is zero,
The words are assigned to sequential indices of the array variable aname,
starting at 0. All elements are removed from aname before the assignment.
unless end-of-file is encountered or read times out.
Other name arguments are ignored. Examples
#!/bin/bash
-d delim read var_year
The first character of delim is used to terminate the input line,
rather than newline.
echo "The year is: $var_year"
echo -n "Enter your name and press [ENTER]: "
-e read var_name
If the standard input is coming from a terminal, Readline is used echo "Your name is: $var_name"
to obtain the line.
-n nchars readonly
read returns after reading nchars characters rather Mark variables/functions as readonly.
than waiting for a complete line of input. Syntax
readonly [-apf] [name] ...
-p prompt
Display prompt, without a trailing newline, before attempting Options
to read any input. The prompt is displayed only if input is coming from a -f Each name refers to a shell function
terminal. -a Each name refers to an array variable
-p Print a list of all readonly names (This is the default)
-r
If this option is given, backslash does not act as an escape character.
The values of these names may not be changed by subsequent assignment.
The backslash is considered to be part of the line. In particular, a
backslash-newline The `-p' option causes output to be displayed in a format that may be reused as input.
pair may not be used as a line continuation.
-s The return status is zero unless an invalid option is supplied, one of the name arguments is not a
Silent mode. If input is coming from a terminal, characters are not echoed. valid shell variable or function name, or the `-f' option is supplied with a name that is not a shell
function.
-t timeout readonly is a BOURNE shell command and a POSIX `special' builtin.
Cause read to time out and return failure if a complete line
of input is not read within timeout seconds. This option has no
effect if read is not reading input from the terminal or a pipe. rename (linux only, not ubuntu)
This is a BASH shell builtin. Rename files.
Syntax
rename from to file...
One line is read from the standard input, and the first word is assigned to the first name, the
rename will rename the specified files by replacing the first occurrence of from in their name by
second word to the second name, and so on, with leftover words and their intervening separators
to.
assigned to the last name.
Examples
If there are fewer words read from the standard input than names, the remaining names are Given the files foo1, ..., foo9, foo10, ..., foo278, the commands
$ rename foo foo0 foo?
assigned empty values.
$ rename foo foo0 foo??
The characters in the value of the IFS variable are used to split the line into words. will turn them into foo001, ..., foo009, foo010, ..., foo278.
Fix the extension of your .htm files so they become .html :
$ rename .htm .html *.htm
rsync [option]... Source [Source]... [user@]host::Dest # List files on a remote machine. This is done the same way as rsync transfers except that you
leave off the local destination.
# Remote to Local
rsync [option]... [user@]host::Source [Dest]
Note that in all cases (other than listing) at least one of the source and destination paths must be
rsync [option]... [user@]host:SourceDest local.
Usage
rsync [option]... rsync://[user@]host[:PORT]/Source [Dest]
You use rsync in the same way you use rcp.
rsync is a program that behaves in much the same way that rcp does, but has many more options You must specify a source and a destination, one of which may be remote.
and uses the rsync remote-update protocol to greatly speed up file transfers when the destination
file already exists. Perhaps the best way to explain the syntax is some examples:
You can also use rsync in local-only mode, where both the source and destination Run the above over a PPP link to a duplicate directory on machine "ss64".
don't have a ':' in the name.
In this case it behaves like an improved copy command. To synchronize samba source trees use the following Makefile targets:
# the remote server may print a message of the day when you connect. Here is a short summary of the options available in rsync.
Please refer to the FULL List of OPTIONS for a complete description.
# if you specify no path name on the remote server then the list of accessible
paths on the server will be shown. What to copy:
-r, --recursive recurse into directories
# if you specify no local destination then a listing of the specified files on -R, --relative use relative path names
the remote server is provided. --exclude=PATTERN exclude files matching PATTERN
--exclude-from=FILE exclude patterns listed in FILE
Some paths on the remote server may require authentication. -I, --ignore-times don't exclude files that match length and time
If so then you will receive a password prompt when you connect. --size-only only use file size when determining if a file should
You can avoid the password prompt by setting the environment variable be transferred
RSYNC_PASSWORD to the password you want to use or using the --password-file --modify-window=NUM Timestamp window (seconds) for file match
option. (default=0)
This may be useful when scripting rsync. --include=PATTERN don't exclude files matching PATTERN
--include-from=FILE don't exclude patterns listed in FILE
WARNING: On some systems environment variables are visible to all users.
On those systems using --password-file is recommended. How to copy it:
-n, --dry-run show what would have been transferred
RUNNING AN RSYNC SERVER -l, --links copy symlinks as symlinks
-L, --copy-links copy the referent of symlinks
An rsync server is configured using a config file which by default is --copy-unsafe-links copy links outside the source tree
called /etc/rsyncd.conf. Please see the rsyncd.conf(5) man page for more --safe-links ignore links outside the destination tree
information. -H, --hard-links preserve hard links
Misc Others: # if the pattern contains a wildcard character from the set *?[ then expression
--address=ADDRESS bind to the specified address matching is applied using the shell filename matching rules.
--blocking-io use blocking IO for the remote shell Otherwise a simple string match is used.
--bwlimit=KBPS limit I/O bandwidth, KBytes per second
--config=FILE specify alternate rsyncd.conf file # if the pattern includes a double asterisk "**" then all wildcards in the
--daemon run as a rsync daemon pattern
--no-detach do not detach from the parent will match slashes, otherwise they will stop at slashes.
--password-file=FILE get password from FILE
--port=PORT specify alternate rsyncd port number # if the pattern contains a / (not counting a trailing /) then it is matched
-f, --read-batch=FILE read batch file against the full filename, including any leading directory.
-F, --write-batch write batch file If the pattern doesn't contain a / then it is matched only against the final
--version print version number component of the filename. Again, remember that the algorithm is applied
-v, --verbose increase verbosity recursively
-q, --quiet decrease verbosity so "full filename" can actually be any portion of a path.
-h, --help show this help screen
# if the pattern starts with "+ " (a plus followed by a space) then it is always
# if the pattern starts with "- " (a minus followed by a space) then it is always Three basic behaviours are possible when rsync encounters a symbolic link in
considered an exclude pattern, even if specified as part of an include option. the source directory.
The "- " part is discarded before matching.
By default, symbolic links are not transferred at all.
# if the pattern is a single exclamation mark ! then the current include/exclude A message "skipping non-regular" file is emitted for any symlinks that exist.
list
is reset, removing all previously defined patterns. If --links is specified, then symlinks are recreated with the same target
on the destination. Note that --archive implies --links.
The +/- rules are most useful in exclude lists, allowing you to have a single
exclude list that contains both include and exclude options. If --copy-links is specified, then symlinks are "collapsed" by copying their
referent,
If you end an exclude list with --exclude '*', note that since the algorithm is rather than the symlink.
applied recursively that unless you explicitly include parent directories of
files you want to include then the algorithm will stop at the parent directories rsync also distinguishes "safe" and "unsafe" symbolic links.
and never see the files below them. To include all directories, use --include An example where this might be used is a web site mirror that wishes ensure the
'*/' before the --exclude '*'. rsync module they copy does not include symbolic links to /etc/passwd in the
public
Here are some exclude/include examples: section of the site. Using --copy-unsafe-links will cause any links to be copied
as the file they point to on the destination.
# --exclude "*.o" would
exclude all filenames matching *.o Using --safe-links will cause unsafe links to be ommitted altogether.
# --exclude "/foo" would
exclude a file in the base directory called foo
# --exclude "foo/" would
exclude any directory called foo. DIAGNOSTICS
# --exclude "/foo/*/bar"
would exclude any file called bar two levels below a
base directory called foo. rsync occasionally produces error messages that may seem a little cryptic.
# --exclude "/foo/**/bar" would exclude any file called bar two or more levels The one that seems to cause the most confusion is
below "protocol version mismatch - is your shell clean?".
a base directory called foo.
# --include "*/" --include "*.c" --exclude "*" This message is usually caused by your startup scripts or remote shell facility
would include all directories producing unwanted garbage on the stream that rsync is using for its transport.
and C source files The way to diagnose this problem is to run your remote shell like this:
# --include "foo/" --include "foo/bar.c" --exclude "*"
would include only foo/bar.c (the foo/ directory must be rsh remotehost /bin/true > out.dat
explicitly included or it would be excluded by the "*")
then look at out.dat. If everything is working correctly then out.dat should be
BATCH MODE a zero length file. If you are getting the above error from rsync then you will
probably find that out.dat contains some text or data.
The following call generates 4 files that encapsulate the information for Look at the contents and try to work out what is producing it.
synchronizing the contents of target_dir with the updates found in src_dir The most common cause is incorrectly configured shell startup scripts
(such as .cshrc or .profile) that contain output statements for non-interactive
$ rsync -F [other rsync options here] \ logins.
/somewhere/src_dir /somewhere/target_dir
If you are having trouble debugging include and exclude patterns,
The generated files are labeled with a common timestamp: then try specifying the -vv option.
At this level of verbosity rsync will show why each individual file is included
# rsync_argvs. command-line arguments or
# rsync_flist. rsync internal file metadata excluded.
# rsync_csums. rsync checksums
# rsync_delta. data blocks for file update & change SETUP
See the file README for installation instructions.
See http://www.ils.unc.edu/i2dsi/unc_rsync+.html for papers and technical
reports. Once installed you can use rsync to any machine that you can use rsh to.
You can also specify an alternative to rsh, either by using the -e command line screen -r [[pid.]tty[.host]]
option, or by setting the RSYNC_RSH environment variable.
screen -r sessionowner/[[pid.]tty[.host]]
One common substitute is to use ssh, which offers a high degree of security.
Options:
Note that rsync must be installed on both the source and destination machines.
-A -[r|R] Adapt all windows to the new display width & height.
ENVIRONMENT VARIABLES -c file Read configuration file instead of .screenrc
-d (-r) Detach the elsewhere running screen (and reattach here).
CVSIGNORE -dmS name Start as daemon: Screen session in detached mode.
The CVSIGNORE environment variable supplements any ignore patterns in -D (-r) Detach and logout remote (and reattach here).
.cvsignore files. -D -RR Do whatever is needed to Reattach a screen session.
See the --cvs-exclude option for more details. -d -m Start in "detached" mode. Useful for system startup scripts.
-D -m Start in "detached" mode, & don't fork a new process.
RSYNC_RSH -list List our SockDir and do nothing else (-ls)
The RSYNC_RSH environment variable allows you to override the default shell -r Reattach to a detached screen process.
used as -R Reattach if possible, otherwise start a new session.
the transport for rsync. This can be used instead of the -e option. -t title Set title. (window's name).
-U Tell screen to use UTF-8 encoding.
RSYNC_PROXY -x Attach to a not detached screen. (Multi display mode).
The RSYNC_PROXY environment variable allows you to redirect your rsync client -X Execute cmd as a screen command in the specified session.
to
use a web proxy when connecting to a rsync daemon. Interactive commands:
You should set RSYNC_PROXY to a hostname:port pair.
Control-a ? Display brief help
RSYNC_PASSWORD Control-a " List all windows for selection
Setting RSYNC_PASSWORD to the required password allows you to run Control-a ' Prompt for a window name or number to switch to.
authenticated Control-a 0 Select window 0
rsync connections to a rsync daemon without user intervention. Control-a 1 Select window 1
Note that this does not supply a password to a shell transport such as ssh. ... ...
Control-a 9 Select window 9
USER or LOGNAME Control-a A Accept a title name for the current window.
The USER or LOGNAME environment variables are used to determine the default Control-a b Send a break to window
username sent to a rsync server. Control-a c Create new window running a shell
Control-a C Clear the screen
HOME Control-a d Detach screen from this terminal.
The HOME environment variable is used to find the user's default .cvsignore Control-a D D Detach and logout.
file. Control-a f Toggle flow on, off or auto.
Control-a F Resize the window to the current region size.
FILES Control-a h Write a hardcopy of the current window to file "hardcopy.n"
Control-a H Begin/end logging of the current window to file "screenlog.n"
/etc/rsyncd.conf Control-a i Show info about this window.
Control-a k Kill (Destroy) the current window.
screen Control-a
Control-a
l
M
Fully refresh current window
Monitor the current window for activity {toggle on/off}
Multiplex a physical terminal between several processes (typically interactive shells). Control-a n Switch to the Next window
Syntax: Control-a N Show the Number and Title of window
Control-a p Switch to the Previous window
Start a screen session: Control-a q Send a control-q to the current window(xon)
Control-a Q Delete all regions but the current one.(only)
screen [ -options ] [ cmd [args] ] Control-a r Toggle the current window's line-wrap setting(wrap)
--minimal
Change the algorithm to perhaps find a smaller set
sed
of changes. This makes sdiff slower (sometimes
SED is a stream editor. A stream editor is used to perform basic text transformations on an input
much slower). stream (a file or input from a pipeline).
While in some ways similar to an editor which permits scripted edits, SED works by making only
-o file one pass over the input(s), and is consequently more efficient. But it is SED's ability to filter text
--output=file
in a pipeline which particularly distinguishes it from other types of editors.
Put merged output into file. This option is SYNTAX
required for merging. sed [options]...
-s OPTIONS
--suppress-common-lines A single command may be specified as the first argument to sed. Multiple commands may be
Do not print common lines. specified by using the -e or -f options. All commands are applied to the input in the order they are
specified regardless of their origin.
--speed-large-files `-e SCRIPT'
Use heuristics to speed handling of large files `--expression=SCRIPT'
that have numerous scattered small changes. Add the commands in SCRIPT to the set of commands to be run while
processing the input.
-t Expand tabs to spaces in the output, to preserve
the alignment of tabs in the input files. `-f SCRIPT-FILE'
`--file=SCRIPT-FILE'
--text Treat all files as text and compare them line-by- Add the commands contained in the file SCRIPT-FILE to the set of
line, even if they do not appear to be text. commands to be run while processing the input.
-v `-n'
`--quiet'
--version `--silent'
Output the version number of sdiff. By default, SED will print out the pattern space at then end of
each cycle through the script. These options disable this
-w columns automatic printing, and SED will only produce output when
--width=columns explicitly told to via the `p' command.
Use an output width of columns. Note that for his-
torical reasons, this option is -W in diff, -w in `-h'
sdiff.
`-V' `p'
`--version' If the substitution was made, then print the new pattern
Print out version info and exit. space.
If no `-e', `-f', `--expression', or `--file' options are given on the command-line, then the first non-
`NUMBER'
option argument on the command line is taken to be the SCRIPT to be executed. If any Only replace the NUMBERth match of the REGEXP.
command-line parameters remain after processing the above, these parameters are interpreted as
the names of input files to be processed. A file name of `-' refers to the standard input stream. The `w FILE-NAME'
standard input will processed if no file names are specified. If the substitution was made, then write out the result to
the named file.
sed supports regular expressions (like awk), and can select whole lines or patterns of text. `I'
e.g. Match REGEXP in a case-insensitive manner.
`/REGEXP/' (This is a GNU extension.)
This will select any line which matches the regular expression
REGEXP. If REGEXP itself includes any `/' characters, each must
be escaped by a backslash (`\').
select
The select construct allows the easy generation of menus. It has almost the same syntax as the
`/REGEXP/I' for command.
`\%REGEXP%I' Syntax
The `I' modifier to regular-expression matching is a GNU extension select name [in words ...]; do commands; done
which causes the REGEXP to be matched in a case-insensitive manner. The list of words following in is expanded, generating a list ofitems. The set of expanded words
Having selected a pattern you can either delete or replace it... is printed on the standard error output stream, each preceded by a number.
`d'
Delete the pattern space; immediately start next cycle.
If the `in words' is omitted, the positional parameters are printed, as if `in "$@"' had
`s/REGEXP/REPLACEMENT/FLAGS' been specifed. The PS3 prompt is then displayed and a line is read from the standard input. If the
(The `/' characters may be uniformly replaced by any other single line consists of a number corresponding to one of the displayed words, then the value of name is
character within any given `s' command.)
The `/' character (or whatever other character is used in its stead) can appear in the REGEXP or set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the
select command completes. Any other value read causes name to be set to null. The line read is
REPLACEMENT only if it is preceded by a `\' character. Also newlines may appear in the
REGEXP using the two character sequence `\n'. saved in the variable REPLY.
The `s' command attempts to match the pattern space against the supplied REGEXP. If the match The commands are executed after each selection until a break or return command is executed, at
is successful, then that portion of the pattern space which was matched is replaced with which point the select command completes.
REPLACEMENT.
Here is an example that allows the user to pick a filename from the current directory, and displays
The REPLACEMENT can contain `\N' (N being a number from 1 to 9, inclusive) references, the name and index of the file selected.
select fname in *;
which refer to the portion of the match which is contained between the Nth `\(' and its matching do
`\)'. echo you picked $fname \($REPLY\)
Also, the REPLACEMENT can contain unescaped `&' characters which will reference the whole break;
done
matched portion of the pattern space. To include a literal `\', `&', or newline in the final
((...))
replacement, be sure to precede the desired `\', `&', or newline in the REPLACEMENT with a `\'. (( expression ))
The `s' command can be followed with zero or more of the following
FLAGS:
If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1.
This is exactly equivalent to
`g' let "expression"
-f FORMAT -B braceexpand
--format=FORMAT The shell will perform brace expansion.
Print all numbers using FORMAT; default `%g'. FORMAT must contain This option is on by default.
exactly one of the standarding float output formats `%e', `%f', or
`%g'. -C noclobber
Prevent output redirection using `>', `>&',
-s STRING and `<>' from overwriting existing files.
--separator=STRING
Separate numbers with STRING; default is a newline. The output -e errexit
always terminates with a newline. Exit immediately if a simple command exits with a non-zero
status, unless the command that fails is part of an until or
-w while loop, part of an if statement, part of a && or || list,
--equal-width or if the command's return status is being inverted using !.
Print all numbers with the same width, by padding with leading
zeroes. (To have other kinds of padding, use `--format'). -f noglob
`seq' prints the numbers from FIRST to LAST by STEP. Disable file name generation (globbing).
-h hashall
By default, FIRST and STEP are both 1, and each number is printed on its own line. All numbers Locate and remember (hash) commands as they are looked
can be reals, not just integers. up for execution. This option is enabled by default.
Examples
Produce a sequence of numbers from 1 to 100 -H histexpand
Enable `!' style history substitution
$ seq 100 This option is on by default for interactive shells.
You can also produce a sequence with the for command
for ((myseq=0; myseq<50; myseq++)) -k keyword
All arguments in the form of assignment statements are
do placed in the environment for a command, not just those that
echo The sequence is ${myseq} precede the command name.
done
fi -m monitor
Job control is enabled.
set -n noexec
Manipulate shell variables and functions. Read commands but do not execute them; this may be used
Syntax to check a script for syntax errors.
set [--abBCefhHkmnpPtuvx] [-o option] [argument ...] This option is ignored by interactive shells.
If no options or arguments are supplied, set displays the names and values of all shell variables -o option-name
and functions, sorted according to the current locale, in a format that may be reused as input. Set the option corresponding to `option-name'
When options are supplied, they set or unset shell attributes. The `option-names' are listed above and below (in ITALICS)
Options
emacs : Use an emacs-style line editing interface .
Using `+' rather than `-' will cause the option to be turned off. history : Enable command history,
this option is on by default in interactive shells.
-- Options
If no arguments follow this option, then the positional parameters are unset.
Otherwise, the positional parameters are set to the arguments, n : The number of parameters to shift (default = 1)
even if some of them begin with a `-'. The positional parameters from
n+1 ... $#
-
are renamed to
Signal the end of options, cause all remaining arguments to be
assigned to the positional parameters. The `-x' and `-v' $1 ... $#-n+1
options are turned off. If there are no arguments, the positional parameters
remain unchanged. Parameters represented by the numbers $# to n+1 are unset.
Examples
Set the variable 'mydept' equal to 'Sales' : n must be a positive number less than or equal to $#.
mydept=Sales
To make the change permanent: The return status is zero unless n is greater than $# or less than zero.
shopt cmdhist
If set, Bash attempts to save all lines of a multiple-line command in the
Shell Options same history entry. This allows easy re-editing of multi-line commands.
Syntax
shopt [-pqsu] [-o] [optname ...] dotglob
If set, Bash includes filenames beginning with a `.' in the results of
Options filename
-s Enable (set) each optname expansion.
checkhash hostcomplete
If this is set, Bash checks that a command found in the hash table exists If set, and Readline is being used, Bash will attempt to perform hostname
before trying to execute it. If a hashed command no longer exists, a normal completion when a word containing a `@' is being completed.
path search is performed. This option is enabled by default.
checkwinsize huponexit
If set, Bash checks the window size after each command and, if necessary, If set, Bash will send SIGHUP to all jobs when an interactive
login shell exits.
sourcepath Key:
If set, the source builtin uses the value of PATH
to find the directory containing the file supplied as an argument. This s : seconds (default)
option
is enabled by default. m : minutes
xpg_echo h : hours
If set, the echo builtin expands backslash-escape sequences
Security Enhanced version of GNU Locate. Secure Locate provides a secure way to index and --verbose Verbose mode. Display files when creating database.
quickly search for files on your system. It uses incremental encoding just like GNU locate to -V
compress its database to make searching faster, but it will also store file permissions and --version Display version.
ownership so that users will not see files they do not have access to. slocate enables system users to search entire filesystems without displaying unauthorized files.
Syntax
slocate [-qi] [-d path] [--database=path] search string sort
Sort text files.
slocate [-i] [-r regexp] [--regexp=regexp]
Sort, merge, or compare all the lines from the files given (or standard input.)
slocate [-qv] [-o file] [--output=file] Syntax
sort [options] [file...]
slocate [-e dir1,dir2,...] [-f fstype1,...] <[-l level] [-c] <[-U path] [- sort --help
u]> sort --version
-u Create slocate database starting at path /. -c Check whether the given files are already sorted: if they are
not all sorted, print an error message and exit with a status of
-U dir Create slocate database starting at path dir. 1.
-e dir1,dir2,... -m Merge the given files by sorting them as a group. Each input
Exclude directories from the slocate database. file should already be individually sorted. It always works to
sort instead of merge; merging is provided because it is faster,
-f fstype1,... in the case where it works.
Exclude files on specific file systems from the slocate The following options affect the ordering of output lines. They may be specified globally or as
database. part of a specific key field. If no key
-c Parse '/etc/updatedb.conf' when updating the slocate database.
fields are specified, global options apply to comparison of entire lines; otherwise the global
options are inherited by key fields that do not
-l level specify any special options of their own. The `-b', `-d', `-f' and `-i' options classify characters
Security level. 0 turns security checks off. according to the `LC_CTYPE' locale.
This will make search faster. 1 turns security checks on. This is the `-b'
default. Ignore leading blanks when finding sort keys in each line.
-i Do a case insensitive search. `-d'
Sort in "phone directory" order: ignore all characters except
-q Quiet mode. Error messages are suppressed. letters, digits and blanks when sorting.
-n num Limit the amount of results shown to num. `-f'
Fold lowercase characters into the equivalent uppercase characters
-r regexp when sorting so that, for example, `b' and `B' sort as equal.
--regexp=regexp Search the database using a basic POSIX regular expression.
`-g'
-o file Sort numerically, using the standard C function `strtod' to convert
--output=file The database to create. a prefix of each line to a double-precision floating point number.
This allows floating point numbers to be specified in scientific
-d path notation, like `1.0e-34' and `10e100'. Do not report overflow,
* Lines that do not start with numbers (all considered to be Other options:
equal).
`-o OUTPUT-FILE'
* NaNs ("Not a Number" values, in IEEE floating point Write output to OUTPUT-FILE instead of standard output. If
arithmetic) in a consistent but machine-dependent order. OUTPUT-FILE is one of the input files, `sort' copies it to a
temporary file before sorting and writing the output to
* Minus infinity. OUTPUT-FILE.
`-i' `-u'
Ignore unprintable characters. For the default case or the `-m' option, only output the first of
a sequence of lines that compare equal. For the `-c' option,
`-M' check that no pair of consecutive lines compares equal.
An initial string, consisting of any amount of whitespace, followed
by a month name abbreviation, is folded to UPPER case and compared `-k POS1[,POS2]'
in the order `JAN' < `FEB' < ... < `DEC'. Invalid names compare The recommended, POSIX, option for specifying a sort field. The
low to valid names. The `LC_TIME' locale determines the month field consists of the part of the line between POS1 and POS2 (or
spellings. the end of the line, if POS2 is omitted), _inclusive_. Fields and
character positions are numbered starting with 1. So to sort on
`-n' the second field, you'd use `-k 2,2' See below for more examples.
Sort numerically: the number begins each line; specifically, it
consists of optional whitespace, an optional `-' sign, and zero or `-z'
more digits possibly separated by thousands separators, optionally Treat the input as a set of lines, each terminated by a zero byte
followed by a radix character and zero or more digits. The (ASCII NUL (Null) character) instead of an ASCII LF (Line Feed).
`LC_NUMERIC' locale specifies the radix character and thousands This option can be useful in conjunction with `perl -0' or `find
separator. -print0' and `xargs -0' which do the same in order to reliably
handle arbitrary pathnames (even those which contain Line Feed
`sort -n' uses what might be considered an unconventional method characters.)
to compare strings representing floating point numbers. Rather
than first converting each string to the C `double' type and then `+POS1[-POS2]'
comparing those values, sort aligns the radix characters in the two The obsolete, traditional option for specifying a sort field.
strings and compares the strings a character at a time. One The field consists of the line between POS1 and up to but _not
benefit of using this approach is its speed. In practice this is including_ POS2 (or the end of the line if POS2 is omitted).
much more efficient than performing the two corresponding Fields and character positions are numbered starting with 0.
string-to-double (or even string-to-integer) conversions and then See below.
comparing doubles. In addition, there is no corresponding loss of
precision. Converting each string to `double' before comparison `--help'
would limit precision to about 16 digits on most systems.
`--version'
Neither a leading `+' nor exponential notation is recognized. To HOW LINES ARE COMPARED
compare such strings numerically, use the `-g' option.
`-r' A pair of lines is compared as follows: if any key fields have been specified, `sort' compares each
If the environment variable `TMPDIR' is set, `sort' uses its value as the directory for temporary In the remaining examples, the POSIX `-k' option is used to specify sort keys rather than the
files instead of `/tmp'. The `-T TEMPDIR' option in turn overrides the environment variable. obsolete `+POS1-POS2' syntax.
Sort in descending (reverse) numeric order:
NOTES
$ sort -nr
Historical (BSD and System V) implementations of `sort' have differed in their interpretation of Sort alphabetically, omitting the first and second fields. This
some options, particularly `-b', `-f', and `-n'. GNU sort follows the POSIX behavior, which is uses a single key composed of the characters beginning at the
usually (but not always!) like the System V behavior. According to POSIX, `-n' no longer implies start of field three and extending to the end of each line:
`-b'. For consistency, `-M' has been changed in the same way. This may affect the meaning of
$ sort -k3
character positions in field specifications in obscure cases. The only fix is to add an explicit `-b'.
Sort numerically on the second field and resolve ties by sorting
A position in a sort field specified with the `-k' or `+' option has the form `F.C', where F is the alphabetically on the third and fourth characters of field five.
number of the field to use and C is the number of the first character from the beginning of the Use `:' as the field delimiter:
field (for `+POS') or from the end of the previous field (for `-POS'). If the `.C' is omitted, it is $ sort -t : -k 2,2n -k 5.3,5.4
taken to be the first character in the field. If the `-b' option was specified, the `.C' part of a field Note that if you had written `-k 2' instead of `-k 2,2' `sort' would have used all characters
specification is counted from the first nonblank character of the field (for `+POS') or from the beginning in the second field and extending to the end of the line as the primary _numeric_ key.
first nonblank character following the previous field (for `-POS'). For the large majority of applications, treating keys spanning more than one field as numeric will
not do what you expect.
A sort key option may also have any of the option letters `Mbdfinr' appended to it, in which case
the global ordering options are not used for that particular field. The `-b' option may be Also note that the `n' modifier was applied to the field-end specifier for the first key. It would
independently attached to either or both of the `+POS' and `-POS' parts of a field specification, have been equivalent to specify `-k 2n,2' or `-k 2n,2n'. All modifiers except `b' apply to the
$ sort -t : -k 5b,5 -k 3,3n /etc/passwd The return status is the exit status of the last command executed, or zero if no commands are
executed. If filename is not found, or cannot be read, the return status is non-zero. `source' is a
An alternative is to use the global numeric modifier `-n':
bourne shell builtin and a POSIX `special' builtin
$ sort -t : -n -k 5b,5 -k 3,3 /etc/passwd
If the ExitOnForwardFailure configuration option is set to “yes”, -M Places the ssh client into “master” mode for connection sharing.
then a client started with -f will wait for all remote port Multiple -M options places ssh into “master” mode with
forwards to be successfully established before placing itself in confirmation required before slave connections are accepted.
the background. Refer to the description of ControlMaster in ssh_config(5) for
details.
-g Allows remote hosts to connect to local forwarded ports.
-m mac_spec
-I smartcard_device
Additionally, for protocol version 2 a comma-separated list of
Specify the device ssh should use to communicate with a smartcard MAC (message authentication code) algorithms can be specified in
used for storing the user‟s private RSA key. This option is only order of preference. See the MACs keyword for more information.
available if support for smartcard devices is compiled in
(default is no support). -N Do not execute a remote command. This is useful for just
forwarding ports (protocol version 2 only).
-i identity_file
Selects a file from which the identity (private key) for RSA or -n Redirects stdin from /dev/null (actually, prevents reading from
DSA authentication is read. The default is ~/.ssh/identity for stdin). This must be used when ssh is run in the background. A
protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for common trick is to use this to run X11 programs on a remote
protocol version 2. Identity files may also be specified on a machine. For example, ssh -n shadows.cs.hut.fi emacs & will
per-host basis in the configuration file. It is possible to have start an emacs on shadows.cs.hut.fi, and the X11 connection will
multiple -i options (and multiple identities specified in be automatically forwarded over an encrypted channel. The ssh
configuration files).
program will be put in the background. (This does not work if
-K Enables GSSAPI-based authentication and forwarding (delegation) ssh needs to ask for a password or passphrase; see also the -f
of GSSAPI credentials to the server. option.)
-T Disable pseudo-tty allocation. ssh exits with the exit status of the remote command or with 255 if an
error occurred.
-t Force pseudo-tty allocation. This can be used to execute AUTHENTICATION
arbitrary screen-based programs on a remote machine, which can be The OpenSSH SSH client supports SSH protocols 1 and 2. Protocol 2 is the
very useful, e.g. when implementing menu services. Multiple -t default, with ssh falling back to protocol 1 if it detects protocol 2 is
unsupported. These settings may be altered using the Protocol option in
options force tty allocation, even if ssh has no local tty. ssh_config(5), or enforced using the -1 and -2 options (see above). Both
protocols support similar authentication methods, but protocol 2 is
-V Display the version number and exit. preferred since it provides additional mechanisms for confidentiality
(the traffic is encrypted using AES, 3DES, Blowfish, CAST128, or Arcfour)
-v Verbose mode. Causes ssh to print debugging messages about its and integrity (hmac-md5, hmac-sha1, umac-64, hmac-ripemd160). Protocol 1
progress. This is helpful in debugging connection, lacks a strong mechanism for ensuring the integrity of the connection.
authentication, and configuration problems. Multiple -v options
increase the verbosity. The maximum is 3. The methods available for authentication are: GSSAPI-based
authentication, host-based authentication, public key authentication,
-w local_tun[:remote_tun] challenge-response authentication, and password authentication.
Requests tunnel device forwarding with the specified tun(4) Authentication methods are tried in the order specified above, though
devices between the client (local_tun) and the server protocol 2 has a configuration option to change the default order:
(remote_tun). PreferredAuthentications.
The devices may be specified by numerical ID or the keyword Host-based authentication works as follows: If the machine the user logs
“any”, which uses the next available tunnel device. If in from is listed in /etc/hosts.equiv or /etc/ssh/shosts.equiv on the
remote_tun is not specified, it defaults to “any”. See also the remote machine, and the user names are the same on both sides, or if the
Tunnel and TunnelDevice directives in ssh_config(5). If the files ~/.rhosts or ~/.shosts exist in the user‟s home directory on the
Tunnel directive is unset, it is set to the default tunnel mode, remote machine and contain a line containing the name of the client
which is “point-to-point”. machine and the name of the user on that machine, the user is considered
for login. Additionally, the server must be able to verify the client‟s
-X Enables X11 forwarding. This can also be specified on a per-host host key (see the description of /etc/ssh/ssh_known_hosts and
basis in a configuration file. ~/.ssh/known_hosts, below) for login to be permitted. This
authentication method closes security holes due to IP spoofing, DNS
X11 forwarding should be enabled with caution. Users with the spoofing, and routing spoofing. [Note to the administrator:
ability to bypass file permissions on the remote host (for the /etc/hosts.equiv, ~/.rhosts, and the rlogin/rsh protocol in general, are
user‟s X authorization database) can access the local X11 display inherently insecure and should be disabled if security is desired.]
through the forwarded connection. An attacker may then be able
to perform activities such as keystroke monitoring. Public key authentication works as follows: The scheme is based on
public-key cryptography, using cryptosystems where encryption and
For this reason, X11 forwarding is subjected to X11 SECURITY decryption are done using separate keys, and it is unfeasible to derive
extension restrictions by default. Please refer to the ssh -Y the decryption key from the encryption key. The idea is that each user
creates a public/private key pair for authentication purposes. The
option and the ForwardX11Trusted directive in ssh_config(5) for server knows the public key, and only the user knows the private key.
more information. ssh implements public key authentication protocol automatically, using
either the RSA or DSA algorithms. Protocol 1 is restricted to using only
-x Disables X11 forwarding. RSA keys, but protocol 2 may use either. The HISTORY section of ssl(8)
(on non-OpenBSD systems, see)
-Y Enables trusted X11 forwarding. Trusted X11 forwardings are not contains a brief discussion of the two algorithms.
On the client:
~/.ssh/authorized_keys /etc/ssh/shosts.equiv
This file is used in exactly the same way as hosts.equiv, but
Lists the public keys (RSA/DSA) that can be used for logging in allows host-based authentication without permitting login with
as this user. The format of this file is described in the rlogin/rsh.
sshd(8) manual page. This file is not highly sensitive, but the
recommended permissions are read/write for the user, and not /etc/ssh/ssh_config
accessible by others.
Systemwide configuration file. The file format and configuration
~/.ssh/config options are described in ssh_config(5).
This is the per-user configuration file. The file format and
configuration options are described in ssh_config(5). Because of /etc/ssh/ssh_host_key
the potential for abuse, this file must have strict permissions: /etc/ssh/ssh_host_dsa_key
read/write for the user, and not accessible by others. It may be /etc/ssh/ssh_host_rsa_key
group-writable provided that the group in question contains only These three files contain the private parts of the host keys and
the user. are used for host-based authentication. If protocol version 1 is
used, ssh must be setuid root, since the host key is readable
~/.ssh/environment only by root. For protocol version 2, ssh uses ssh-keysign(8) to
Contains additional definitions for environment variables; see access the host keys, eliminating the requirement that ssh be
ENVIRONMENT, above. setuid root when host-based authentication is used. By default
ssh is not setuid root.
~/.ssh/identity
/etc/ssh/ssh_known_hosts
~/.ssh/id_dsa
~/.ssh/id_rsa Systemwide list of known host keys. This file should be prepared
Contains the private key for authentication. These files contain by the system administrator to contain the public host keys of
sensitive data and should be readable by the user but not all machines in the organization. It should be world-readable.
accessible by others (read/write/execute). ssh will simply See sshd(8) for further details of the format of this file.
ignore a private key file if it is accessible by others. It is
possible to specify a passphrase when generating the key which /etc/ssh/sshrc
will be used to encrypt the sensitive part of this file using Commands in this file are executed by ssh when the user logs in,
3DES. just before the user‟s shell (or command) is started. See the
sshd(8) manual page for more information.
~/.ssh/identity.pub
~/.ssh/id_dsa.pub
~/.ssh/id_rsa.pub
su
Substitute user identity
Contains the public key for authentication. These files are not Run a command with substitute user and group id, allow one user to temporarily become another
sensitive and can (but need not) be readable by anyone. user. It runs a command (often an interactive shell) with the real and effective user id, group id,
~/.ssh/known_hosts and supplemental groups of a given user.
Contains a list of host keys for all hosts the user has logged Syntax
into that are not already in the systemwide list of known host su [options]... [user [arg]...]
keys. See sshd(8) for further details of the format of this
file. Options
~/.ssh/rc -c COMMAND
Commands in this file are executed by ssh when the user logs in, --command=COMMAND
just before the user‟s shell (or command) is started. See the Pass COMMAND, a single command line to run, to the shell with a
sshd(8) manual page for more information. -c option instead of starting an interactive shell.
-m sudoedit [-S] [-a auth_type] [-p prompt] [-u username|#uid] file [...]
-p
--preserve-environment Options
Do not change the environment variables `HOME', `USER', `LOGNAME', -H Set the HOME environment variable to the homedir of the target user
or `SHELL'. Run the shell given in the environment variable (root by default) as specified in passwd(5). By default, sudo does
`SHELL' instead of the shell from USER's passwd entry, unless the not modify HOME (see set_home and always_set_home in sudoers(5)).
user running `su' is not the superuser and USER's shell is
restricted. A "restricted shell" is one that is not listed in the -K (sure kill) like kill (-k) except that it removes the user's timestamp
file `/etc/shells', or in a compiled-in list if that file does not entirely. Like -k, this option does not require a password.
exist. Parts of what this option does can be overridden by
`--login' and `--shell'. -L list defaults, list out the parameters that may be set in a Defaults
line along with a short description for each. This option is useful
-s SHELL in conjunction with grep(1).
--shell=SHELL
Run SHELL instead of the shell from USER's passwd entry, unless -P Preserve group vector, causes sudo to preserve the invoking user's
the user running `su' is not the superuser and USER's shell is group vector unaltered. By default, sudo will initialize the group
restricted (see `-m' just above). vector to the list of groups the target user is in. The real and
If no user is given, the default is 'root', the super-user. effective group IDs, however, are still set to match the target user.
-S stdin, read the password from the standard input instead of the terminal.
The shell to use is taken from user's 'passwd' entry, or /bin/sh if none is specified there.
-V Version, print the version number and exit.
If USER has a password, `su' prompts for the password unless run by a user with effective user id If the invoking user is already root the -V option will print out a
list of the defaults sudo was compiled with as well as the machine's
of zero (the super-user). local network addresses.
By default, su does not change the current directory. It sets the environment variables `HOME' -a Authentication type, use the specified authentication type when
and `SHELL' from the password entry for USER, and if USER is not the super-user, sets `USER' validating the user, as allowed by /etc/login.conf. The system
administrator may specify a list of sudo-specific authentication
and `LOGNAME' to USER. methods by adding an "auth-sudo" entry in /etc/login.conf.
This option is only available on systems that support BSD
By default, the shell is not a login shell. Any additional ARGs are passed as additional arguments authentication where sudo has been configured with the
--with-bsdauth option.
to the shell.
sum Symbolic links may contain .. path components, which (if used at the start of the link) refer to the
parent directories of that in which the link resides.
Print a checksum for a file.
A symbolic link (also known as a soft link) may point to an existing file or to a nonexistent one;
`sum' is provided for compatibility; `cksum' is preferable in new applications.
Syntax the latter case is known as a dangling link.
sum [options]... [file]...
The permissions of a symbolic link are irrelevant; the ownership is ignored when following the
Options link, but is checked when removal or renaming of the link is requested and the link is in a
-r directory with the sticky bit set.
Use the default (BSD compatible) algorithm. This option is
included for compatibility with the System V `sum'. Unless `-s' If NewPath exists it will NOT be overwritten.
was also given, it has no effect. RETURN VALUE
On success, zero is returned. On error, -1 is returned,
-s and errno is set appropriately.
--sysv
Compute checksums using an algorithm compatible with System V ERRORS
`sum''s default, and print file sizes in units of 512-byte blocks. EPERM The filesystem containing NewPath does not support
`sum' prints the checksum for each FILE followed by the number of blocks in the file (rounded the creation of symbolic links.
up). If more than one FILE is given, file names are also printed (by default). (With the `--sysv'
EFAULT OldPath or NewPath points outside your accessible
option, corresponding file name are printed when there is at least one file argument.) address space.
By default, GNU `sum' computes checksums using an algorithm compatible with BSD `sum' and EACCES Write access to the directory containing NewPath is
prints file sizes in units of 1024-byte blocks. not allowed for the process's effective uid, or one
--checkpoint
If you don't specify this argument, then `tar' will use a default, usually some physical tape drive This option directs `tar' to print periodic checkpoint messages as
attached to your machine. If there is no tape drive attached, or the default is not meaningful, then it reads through the archive. Its intended for when you want a
`tar' will print an error message like one of the following: visual indication that `tar' is still running, but don't want to
tar: can't open /dev/rmt8 : No such device or address see --verbose' output.
tar: can't open /dev/rsmt0 : I/O error
--compress
To avoid confusion, we recommend that you always specify an archive file name by using `-- --uncompress
file=ARCHIVE-NAME' (or `-f ARCHIVE-NAME') when writing your `tar' commands. -Z
--verbose' (`-v') shows details about the results of running `tar'. `tar' will use the `compress' program when reading or writing the
This can be especially useful when the results might not be obvious. For example, if you want to archive. This allows you to directly act on archives while saving
see the progress of `tar' as it writes files into the archive, you can use the `--verbose' option. In the space.
beginning, you may find it useful to use `--verbose' at all times; when you are more accustomed --confirmation
to `tar', you will likely want to use it at certain times but not at others. (See --interactive.)
--directory=DIR --ignore-umask
-C DIR (See --preserve-permissions'; *note Writing::..)
When this option is specified, `tar' will change its current
directory to DIR before performing any operations. When this --ignore-zeros
option is used during archive creation, it is order sensitive. -i
With this option, `tar' will ignore zeroed blocks in the archive,
--exclude=PATTERN which normally signals EOF. *Note Reading::.
When performing operations, `tar' will skip files that match
PATTERN. --incremental
-G
--exclude-from=FILE Used to inform `tar' that it is working with an old GNU-format
-X FILE incremental backup archive. It is intended primarily for backwards
Similar to --exclude, except `tar' will use the list of patterns compatibility only.
in the file FILE.
--info-script=SCRIPT-FILE
--file=ARCHIVE --new-volume-script=SCRIPT-FILE
-f ARCHIVE -F SCRIPT-FILE
`tar' will use the file ARCHIVE as the `tar' archive it performs When `tar' is performing multi-tape backups, SCRIPT-FILE is run at
operations on, rather than `tar''s compilation dependent default. the end of each tape.
--files-from=FILE --interactive
-T FILE --confirmation
`tar' will use the contents of FILE as a list of archive members -w
or files to operate on, in addition to those specified on the Specifies that `tar' should ask the user for confirmation before
command-line. performing potentially destructive options, such as overwriting
files.
--force-local
Forces `tar' to interpret the filename given to --file as a local --keep-old-files
file, even if it looks like a remote tape drive name. -k
When extracting files from an archive, `tar' will not overwrite
--group=GROUP existing files if this option is present. *Note Writing::.
Files added to the `tar' archive will have a group id of GROUP,
rather than the group from the source file. GROUP is first decoded --label=NAME
as a group symbolic name, but if this interpretation fails, it has -V NAME
to be a decimal numeric group ID. When creating an archive, instructs `tar' to write NAME as a name
record in the archive. When extracting or listing archives, `tar'
Also see the comments for the --owner=USER option. will only operate on archives that have a label matching the
pattern specified in NAME.
--gzip
--gunzip --listed-incremental=SNAPSHOT-FILE
--ungzip -g SNAPSHOT-FILE
-z During a --create' operation, specifies that the archive that
This option tells `tar' to read or write archives through `gzip', `tar' creates is a new GNU-format incremental backup, using
allowing `tar' to directly operate on several kinds of compressed SNAPSHOT-FILE to determine which files to backup. With other
archives transparently. operations, informs `tar' that the archive is in incremental
format.
--help
`tar' will print out a short message summarizing the operations and --mode=PERMISSIONS
options to `tar' and exit. When adding files to an archive, `tar' will use PERMISSIONS for
Of course, PERMISSIONS might be plainly specified as an octal There is no value indicating a missing number, and `0' usually
number. However, by using generic symbolic modifications to mode means `root'. Some people like to force `0' as the value to offer
bits, this allows more flexibility. For example, the value `a+rw' in their distributions for the owner of files, because the `root'
adds read and write permissions for everybody, while retaining user is anonymous anyway, so that might as well be the owner of
executable bits on directories or on any other file already marked anonymous archives.
as executable.
--portability
--multi-volume --old-archive
-M -o
Informs `tar' that it should create or otherwise operate on a Tells `tar' to create an archive that is compatible with Unix V7
multi-volume `tar' archive. `tar'.
--new-volume-script --posix
(see -info-script) Instructs `tar' to create a POSIX compliant `tar' archive.
--newer=DATE --preserve
--after-date=DATE Synonymous with specifying both --preserve-permissions' and
-N --same-order.
When creating an archive, `tar' will only add files that have
changed since DATE. --preserve-order
(See --same-order; *note Reading::..)
--newer-mtime
In conjunction with --newer', `tar' will only add files whose --preserve-permissions
contents have changed (as opposed to just --newer', which will --same-permissions
also back up files for which any status information has changed). -p
When `tar' is extracting an archive, it normally subtracts the
--no-recursion users' umask from the permissions specified in the archive and
With this option, `tar' will not recurse into directories unless a uses that number as the permissions to create the destination
directory is explicitly named as an argument to `tar'. file. Specifying this option instructs `tar' that it should use
the permissions directly from the archive. *Note Writing::.
--null
When `tar' is using the --files-from' option, this option --read-full-records
instructs `tar' to expect filenames terminated with `NUL', so -B
`tar' can correctly work with file names that contain newlines. Specifies that `tar' should reblock its input, for reading from
pipes on systems with buggy implementations. *Note Reading::.
--numeric-owner
This option will notify `tar' that it should use numeric user and --record-size=SIZE
group IDs when creating a `tar' file, rather than names. Instructs `tar' to use SIZE bytes per record when accessing the
archive.
--old-archive
(See --portability.) --recursive-unlink
Similar to the --unlink-first option, removing existing
--one-file-system directory hierarchies before extracting directories of the same
-l name from the archive. *Note Writing::.
Used when creating an archive. Prevents `tar' from recursing into
directories that are on different file systems from the current --remove-files
directory. Directs `tar' to remove the source file from the file system after
appending it to an archive.
--same-order --uncompress
--preserve-order (See --compress.)
-s
This option is an optimization for `tar' when running on machines --ungzip
with small amounts of memory. It informs `tar' that the list of (See --gzip.)
file arguments has already been sorted to match the order of files
in the archive. *Note Reading::. --unlink-first
-U
--same-owner Direct `tar' to remove the corresponding file from the file system
When extracting an archive, `tar' will attempt to preserve the before extracting it from the archive. *Note Writing::.
owner specified in the `tar' archive with this option present.
--use-compress-program=PROG
--same-permissions Instruct `tar' to access the archive through PROG, which is
(See --preserve-permissions; *note Writing::..) presumed to be a compression program of some sort.
--show-omitted-dirs --verbose
Instructs `tar' to mention directories its skipping over when -v
operating on a `tar' archive. Be more verbose about the operation.
This option can be specified multiple times (for some operations)
--sparse to increase the amount of information displayed.
-S
Invokes a GNU extension when adding files to an archive that --verify
handles sparse files efficiently. -W
Verify that the archive was correctly written.
--starting-file=NAME
-K NAME --version
This option affects extraction only; `tar' will skip extracting `tar' will print an informational message about what version it is
files in the archive until it finds one that matches NAME. *Note and a copyright message, some credits, and then exit.
Scarce::.
--volno-file=FILE
--suffix=SUFFIX Used in conjunction with --multi-volume'. `tar' will keep track
Alters the suffix `tar' uses when backing up files from the default of which volume of a multi-volume archive its working in FILE.
`~'. Examples
--tape-length=NUM
Create a tar and zip the file (using the create function)
tar -czvf MyArchive Source_file
-L NUM
or
Specifies the length of tapes that `tar' is writing as being
tar --create --gzip --verbose --file=MyArchive Source_file
NUM x 1024 bytes long.
Extract the zip file created above:
--to-stdout tar -xzvf MyArchive Source_file
-O or
During extraction, `tar' will extract files to stdout rather than tar --extract --gunzip --verbose --file=MyArchive Source_file
to the file system. *Note Writing::. Create a tar in zip format with the file named as todays date/time:
tar czvf my_backup.$(date +%Y%m%d-%H%M%S).tgz /users/simon
--totals A simple shell script for the above:
Displays the total number of bytes written after creating an #!/bin/bash
archive. tar czvf $1.$(date +%Y%m%d-%H%M%S).tgz $1
exit $?
--touch
%U Total number of CPU-seconds that the process used directly (in user Command Info
mode), in seconds.
%C Name and command line arguments of the command being timed.
%P Percentage of the CPU that this job got. This is just user +
system times divied by the total running time. %x Exit status of the command.
Memory Resources
Examples
%M Maximum resident set size of the process during its lifetime, in
Kilobytes. Run the command `wc /etc/hosts' and show the default information:
%D Average size of the process's unshared data area, in Kilobytes. Run the command `ls -Fs' and show the user, system, and wall-clock time:
%p Average size of the process's unshared stack, in Kilobytes. $ time -f "\t%E real,\t%U user,\t%S sys" ls -Fs
total 16
%X Average size of the process's shared text, in Kilobytes. 1 account/ 1 db/ 1 mail/ 1 run/
1 backups/ 1 emacs/ 1 msgs/ 1 rwho/
%Z System's page size, in bytes. This is a per-system constant, but 1 crash/ 1 games/ 1 preserve/ 1 spool/
varies between systems. 1 cron/ 1 log/ 1 quotas/ 1 tmp/
0:00.03 real, 0.00 user, 0.01 sys
I/O Resources
Run the command `cat' and record the elapsed time (stopwatch) until `cat' is
%F Number of major, or I/O-requiring, page faults that occurred while closed with Ctrl-D
the process was running. These are faults where the page has
actually migrated out of primary memory. $ time cat
^d
%R Number of minor, or recoverable, page faults. These are pages 0:16.55, 726
that are not valid (so they fault) but which have not yet been
claimed by other virtual pages. Thus the data in the page is
still valid but the system tables must be updated.
touch
Change file timestamps, change the access and/or modification times of the specified files.
%W Number of times the process was swapped out of main memory. Syntax
touch [options]... File...
%c Number of times the process was context-switched involuntarily
(because the time slice expired). Options
\OOO
tr The character with the value given by OOO, which is 1 to 3
octal digits,
Translate, squeeze, and/or delete characters
Syntax \\
tr [options]... SET1 [SET2] A backslash.
`tr' copies standard input to standard output, performing one of the following operations:
* translate, and optionally squeeze repeated characters in the result, Ranges
The notation `M-N' expands to all of the characters from M through N, in ascending order. M
* squeeze repeated characters, should collate before N; if it doesn't, an error results. As an example, `0-9' is the same as
`0123456789'. Although GNU `tr' does not support the System V syntax that uses square brackets
* delete characters, to enclose ranges, translations
specified in that format will still work as long as the brackets in STRING1 correspond to identical
* delete characters, then squeeze repeated characters from the result. brackets in STRING2.
Repeated characters
The SET1 and (if given) SET2 arguments define ordered sets of characters, referred to below as
The notation `[C*N]' in SET2 expands to N copies of character C. Thus, `[y*6]' is the same as
SET1 and SET2. These sets are the characters of the input that `tr' operates on. The `--
`yyyyyy'. The notation `[C*]' in STRING2 expands to as many copies of C as are needed to make
complement' (`-c') option replaces SET1 with its complement (all of the characters that are not in
SET2 as long as SET1. If N begins with `0', it is interpreted in octal, otherwise in decimal.
SET1). Character classes
Specifying sets of characters The notation `[:CLASS:]' expands to all of the characters in the (predefined) class CLASS. The
characters expand in no particular
The format of the SET1 and SET2 arguments resembles the format of regular expressions; order, except for the `upper' and `lower' classes, which expand in ascending order. When the `--
however, they are not regular expressions, only lists of characters. Most characters simply delete' (`-d') and `--squeeze-repeats' (`-s') options are both given, any character class can be used
represent themselves in these strings, but the strings can contain the shorthands listed below, for in SET2. Otherwise, only the character classes `lower' and `upper' are accepted in SET2, and then
convenience. Some of them can be used only in SET1 or SET2, as noted below. only if the
Backslash escapes
A backslash followed by a character not listed below causes an corresponding character class (`upper' and `lower', respectively) is specified in the same relative
error message. position in SET1. Doing this specifies case conversion. The class names are given below; an error
results when an invalid class name is given.
\a `alnum'
Control-G. Letters and digits.
\b `alpha'
Control-H. Letters.
\f `blank'
Control-L. Horizontal whitespace.
\n `cntrl'
Control-J. Control characters.
\r `digit'
Control-M. Digits.
`space' Acting like System V `tr' in this case breaks the relatively common BSD idiom:
Horizontal or vertical whitespace.
`upper'
tr -cs A-Za-z0-9 '\012'
Uppercase letters.
because it converts only zero bytes (the first element in the complement of SET1), rather than all
`xdigit' non-alphanumerics, to newlines.
Hexadecimal digits.
#!/bin/sh
cat "$@" \
tsort
| tr -s '[:punct:][:blank:]' '\n' \ Topological sort, perform a topological sort on the given FILE, or standard input if no input file is
| tr '[:upper:]' '[:lower:]' \ given or for a FILE of `-'.
| uniq -d Syntax
Warning messages tsort [options] [file]
Options
Setting the environment variable `POSIXLY_CORRECT' turns off the following warning and
error messages, for strict compliance with POSIX.2. Otherwise, the following diagnostics are --help
issued: --version
true tty
Print file name of terminal on standard input, print the file name of the terminal connected to
Do nothing, returning a zero (true) exit status
`true' does nothing except return an exit status of 0, meaning standard input. It prints `not a tty' if standard input is not a terminal.
"success". It can be used as a place holder in shell scripts where a SYNTAX
tty [option]...
-a Remove All aliases The first word of the replacement text is tested for aliases, but a word that is identical to an alias
If arguments are supplied, an alias is defined for each name whose value is given. being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for
If no value is given, `alias' will print the current value of the alias. instance, and Bash does not try to recursively expand the replacement text.
Without arguments or with the `-p' option, alias prints the list of aliases on the standard output in If the last character of the alias value is a space or tab character, then the next command word
a form that allows them to be reused as input. following the alias is also checked for alias expansion.
name may not be `alias' or `unalias'.
unalias may be used to remove each name from the list of defined aliases. There is no mechanism for using arguments in the replacement text, as in csh. If arguments are
Examples needed, a shell function should be used . Aliases are not expanded when the shell is not
Create an alias 'ls' that will change the default action of ls: interactive, unless the expand_aliases shell option is set using shopt .
$ alias ls='ls --classify'
$ ls The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads
$ unalias ls at least one complete line of input before executing any of the commands on that line. Aliases are
More aliases for ls: expanded when a command is read, not when it is executed. Therefore, an alias definition
$ alias la='ls -lAXh --color=always' #Show all, sort by extension appearing on the same line as another command does not take effect until the next line of input is
$ alias ls-al='ls -al' #fix typo missing space read. The commands following the alias definition on that line are not affected by the new alias.
$ alias l="ls -l" This behavior is also an issue when functions are executed. Aliases are expanded when a function
$ alias la="ls -la" definition is read, not when the function is executed, because a function definition is itself a
Use alias to fix missing space typos: compound command. As a consequence, aliases defined in a function are not available until after
$ alias cd..='cd ..' that function is executed. To be safe, always put alias definitions on a separate line, and do not
$ alias ..='cd ..' use alias in compound commands.
Display the working directory `alias' and `unalias' are BASH built-ins. For almost every purpose, shell functions are preferred
$ alias .='echo $PWD' over aliases.
Prevent accidental deletions by making rm interactive:
$ alias rm='rm -i' uname
Bash programming for linux | nubielab.com 159
Print system information, print information about the machine and operating system it is run on.
-TAB1[,TAB2]...
If no options are given, `uname' acts as if the `-s' option were given. -t TAB1[,TAB2]...
Syntax --tabs=TAB1[,TAB2]...
uname [options]...
If only one tab stop is given, set the tabs TAB1 spaces apart
instead of the default 8. Otherwise, set the tabs at columns
Options
TAB1, TAB2, ... (numbered from 0), and leave spaces and tabs
beyond the tabstops given unchanged. If the tabstops are specified
-a
with the `-t' or `--tabs' option, they can be separated by blanks
--all
as well as by commas. This option implies the `-a' option.
Print all of the below information.
-a
-m
--all
--machine
Convert all strings of two or more spaces or tabs, not just initial
Print the machine (hardware) type.
ones, to tabs.
-n By default, `unexpand' converts only initial spaces and tabs (those that precede all non space or
--nodename tab characters) on each line.
Print the machine's network node hostname. It preserves backspace characters in the output; they decrement the column count for tab
-p
calculations.
--processor By default, tabs are set at every 8th column.
Print the machine's processor type
-r
uniq
--release Uniquify files, write out the unique lines from the given InputFile.
Print the operating system release. If an InputFile of `-' (or nothing) is given, then uniq will read from standard input.
Syntax
-s uniq [options]... [InputFile [OutputFile]]
--sysname
Print the operating system name. Options
-v -N
Print the operating system version. -f N
If multiple options or `-a' are given, the selected information is printed in this order: --skip-fields=N
Skip N fields on each line before checking for uniqueness. Fields
are sequences of non-space non-tab characters that are separated
SYSNAME NODENAME RELEASE OSVERSION MACHINE from each other by at least one spaces or tabs.
+N
The OSVERSION, at least, may well be multiple words.
-s N
For example: --skip-chars=N
$uname -a Skip N characters before checking for uniqueness. If you use both
=> Linux hayley 1.0.4 #3 Thu May 12 18:06:34 1994 i486 the field and character skipping options, fields are skipped over
first.
unexpand -c
Convert spaces to tabs, write the contents of each given FILE, or standard input if none are given --count
or for a FILE of `-', to standard output. Strings of two or more space or tab characters are Print the number of times each line occurred along with the line.
converted to as many tabs as possible followed by as many spaces as are needed. -i
Syntax --ignore-case
unexpand [options]... [file]... Ignore differences in case when comparing lines.
Options
-u -h
--unique --help
Print only unique lines. Print out a summary of the options for `units'.
-w N -q
--check-chars=N --quiet
Compare N characters on each line (after skipping any specified --silent
fields and characters). By default the entire rest of the lines Suppress prompting of the user for units and the display of
are compared. statistics about the number of units loaded.
By default, `uniq' prints the unique lines in a sorted file, i.e., discards all but one of identical
-s
successive lines. Optionally, it can instead show only lines that appear exactly once, or lines that --strict
appear more than once. Suppress conversion of units to their reciprocal units.
The input must be sorted. If your input is not sorted, perhaps you want to use `sort -u'. -v
--verbose
Give slightly more verbose output when converting units. When
If no OutputFile file is specified, `uniq' writes to standard output. combined with the `-c' option this gives the same effect as
`--check-verbose'.
units -V
Convert units from one scale to another. The units are defined in an external data file. You can --version
use the extensive data file that comes with this program, or you can provide your own data file to Print program version number, tell whether the readline library
suit your needs. You can use the program interactively with prompts, or you can use it from the has been included, and give the location of the default units data
file.
command line.
Syntax To invoke units for interactive use, type `units' at your shell prompt. The program will print
units options [FROM-UNIT [TO-UNIT]] something like this:
Options
1161 units, 53 prefixes
-c You have:
--check
Check that all units and prefixes defined in the units file reduce At the `You have:' prompt, type the quantity and units that you are converting *from*. For
to primitive units. The program will print a list of all units
that cannot be reduced. example, if you want to convert ten meters to feet, type `10 meters'. Next, `units' will print `You
want:'. You should type the type of units you want to convert *to*. To convert to feet, you would
--check-verbose type `feet'.
Like the `-check' option, this option prints a list of units that
cannot be reduced. But to help find unit definitions that cause
endless loops, it lists the units as they are checked. If `units' The answer will be displayed in two ways. The first line of output, which is marked with a `*' to
hangs, then the last unit to be printed has a bad definition. indicate multiplication, gives the result of the conversion you have asked for. The second line of
output, which is marked with a `/' to indicate division, gives the inverse of the conversion factor.
-o format
If you convert 10 meters to feet, `units' will print
Bash programming for linux | nubielab.com 161
Multiplication has a higher precedence than division and is evaluated left to right, so `m/s * s/day'
* 32.808399 is equivalent to `m / s s day' and has dimensions of length per time cubed. In effect, the first `/'
/ 0.03048 character marks the beginning of the denominator of your unit. In particular, this means that
writing `1/2 meter' refers to a unit of reciprocal length equivalent to .5/meter, which is probably
which tells you that 10 meters equals about 32.8 feet. The second number gives the conversion in not what you would intend if you entered that expression. To indicate division of numbers, use
the reverse direction. the vertical dash (`|'). No spaces area permitted on either side of the vertical dash character.
You have: 1|2 inch
You want: cm
The `units' program can perform units conversions non-interactively from the command line. To * 1.27
do this, type the command, type the original units expression, and type the new units you want. / 0.78740157
You will probably need to protect the units expressions from interpretation by the shell using Prefixes are defined separately from base units. In order to get centimeters, the units database
single quote characters. defines `centi-' and `c-' as prefixes.
If you type Prefixes can appear alone with no unit following them. An exponent applies only to the
immediately preceding unit and its prefix so that `cm^3' or `centimeter^3' refer to cubic
units '2 liters' 'quarts' centimeters but `centi-meter^3' refers to hundredths of cubic meters. Only one prefix is permitted
per unit, so `micromicrofarad' will fail, but `micro-microfarad' will work.
then `units' will print
For `units', numbers are just another kind of unit. They can appear as many times as you like and
* 2.1133764 in any order in a unit expression. For example, to find the volume of a box which is 2 ft by 3 ft by
/ 0.47317647 12 ft in steres, you could do the following:
You have: 2 ft 3 ft 12 ft
and then exit. The output tells you that 2 liters is about 2.1 quarts, or alternatively that a quart is You want: stere
* 2.038813
about 0.47 times 2 liters. / 0.49048148
Unit expressions
You have: $ 5 / yard
In order to enter more complicated units or fractions, you will need to use operations such as You want: cents / inch
* 13.888889
powers, products and division. Powers of units can be specified using the `^' character as shown / 0.072
in the following example, or by simple concatenation: `cm3' is equivalent to `cm^3'. If the And the second example shows how the dollar sign in the units conversion can precede the five.
exponent is more than one digit, the `^' is required. Be careful: `units' will interpret `$5' with no space as equivalent to dollars^5.
You have: cm^3
You want: gallons
* 0.00026417205 Outside of the SI system, it is often desirable to add values of different units together. Sums of
/ 3785.4118 conformable units are written with the `+' character.
You have: 2 hours + 23 minutes + 32 seconds
You have: arabicfoot-arabictradepound-force You want: seconds
You want: ft lbf * 8612
* 0.7296 / 0.00011611705
/ 1.370614
You have: 12 ft + 3 in
Multiplication of units can be specified by using spaces, a hyphen You want: cm
(`-') or an asterisk (`*'). Division of units is indicated by the * 373.38
slash (`/'). / 0.0026782366
The option `-f' is provided for a more unique interface. Many -d dir Home directory.
programs (such as `cp' and `mv') use this option to trigger the The default is to use user as the directory name
very same action. under the home directory specified with the -D option.
Option `-e' is internally equivalent to `-E "exit 0"'. -g group Initial group name or ID number.
If a different default group has not been specified using the -D
-E STRING option,
--split-at=STRING the default group is 1.
This option works like `-e', but it allows you to specify the -G groups Supplementary groups given by name or number in a comma-separated
string that separates archives if `exit 0' isn't appropriate. list with no whitespace.
For example, noticing that most `.signatures' have a `--' on a -k [dir] Copy default files to user's home directory.
line right before them, one can sometimes use `--split-at=--' for Meaningful only when used with the -m option.
splitting shell archives which lack the `exit 0' line at end. The Default files are copied from /etc/skel/ unless an alternate dir
signature will then be skipped altogether with the headers of the is specified.
following message.
-m Make user's home directory if it does not exist.
--version The default is not to make the home directory.
Print the version number of the program on standard output, then
immediately exits. -o Override. Accept a nonunique uid with the -u option. (Probably a
bad idea.)
--help
Print a help summary on standard output, then immediately exits. -s shell Login shell.
until -u uid
is used.
Numerical user ID. The value must be unique unless the -o option
Execute consequent-commands as long as test-commands has an exit status which is not zero. The default value is the smallest ID value greater than 99 and
Syntax greater
until test-commands; do consequent-commands; done than every other uid.
The return status is the exit status of the last command executed in consequent-commands, or zero
if none was executed. -D [options] Set or display defaults. If options are specified, set them.
If no options are specified, display current defaults. The
useradd options are:
Create new user accounts or update default account information. -b dir Home directory prefix to be used in creating home
Unless invoked with the -D option, user must be given. useradd will create new entries in system directories.
If the -d option is not used when creating an
files. Home directories and initial files may also be created as needed. account, the
Syntax user name will be appended to dir.
useradd [options] [user]
-f days Permanently disable account this many days after the Uuencode reads file (or by default the standard input) and writes an encoded version to the
password has expired. A value of -1 disables this feature. standard output. The encoding uses only printing ASCII characters and includes the mode of the
This option requires the use of shadow passwords. file and the operand name for use by uude code.
-g group Initial group name or ID number.
If name is /dev/stdout the result will be written to standard output.
If a different default group has not been specified using the -D By default the standard UU encoding format will be used. If the option -m is given on the
option, command line base64 encoding is used instead.
Uudecode transforms uuencoded files (or by default, the standard input) into the original form.
-G groups Supplementary groups given by name or number in a comma-separated
list with no whitespace. The user will be removed from any groups The resulting file is named name (or outfile if the -o option is given) and will have the mode of
to the original file except that setuid and execute bits are not retained.
which they currently belong that are not included in groups. If outfile or name is /dev/stdout the result will be written to standard output. Uudecode ignores
any leading and trailing lines. The program can automatically decide which of the both supported
-l name Login name. This cannot be changed while the user is logged in.
encoding schemes are used.
-o Override. Accept a nonunique uid with the -u option. (Probably a Examples
bad idea.) The following example packages up a source tree, compresses it, uuencodes it and mails it to a
-s shell Login shell.
user on another system. When uudecode is run on the target system, the file `src_tree.tar.Z' will
be created which may then be uncompressed and extracted into the original tree.
-u uid Numerical user ID. The value must be unique unless the -o option tar cf - src_tree | compress | uuencode
is used. src_tree.tar.Z | mail sys1!sys2!user
The default value is the smallest ID value greater than 99 and
greater
than every other uid.
VI Editor Commands
Bash programming for linux | nubielab.com 165
Vi has two modes insert mode and command mode. If no delay is specified, only one report is printed with the average
values since boot.
The editor begins in command mode, where cursor movement and copy/paste editing occur.
Most commands execute as soon as typed except for "colon" commands which execute when you count The number of updates. If no count is specified and delay is defined,
press the return key. count defaults to infinity.
:syntax on Turn on syntax highlighting
-d Report disk statistics (2.5.70 or above required)
:syntax off Turn off syntax highlighting
:set number Turn on Line numbering (shorthand :set nu) -p followed by some partition name for detailed statistics (2.5.70 or above
:set nonumber Turn off Line numbering (shorthand :set nonu) required)
:set ignorecase Ignore case sensitivity when searching
-S followed by k or K or m or M switches outputs between 1000, 1024, 1000000,
:set noignorecase Restore case sensitivity (default) or 1048576 bytes
--tty-only
Stop processing options on the right if not on tty.
while
Execute consequent-commands as long as test-commands has an exit status of zero
xdg-open
Open a file or URL in the user's preferred application.
Syntax
xdg-open file
xdg-open URL
xdg-open --help
xdg-open --manual
xdg-open --version
Options:
files The filename(s) to open, wildcards are accepted.
If a URL is provided the URL will be opened in the user's preferred web browser. If a file is
provided the file will be opened in the preferred application for files of that type. xdg-open
supports file, ftp, http and https URLs.
xdg-open is for use inside a desktop session only. It is not recommended to use xdg-open as root.
Exit Codes
A non-zero exit code indicates failure:
0 Success
1 Error in command line syntax.
2 One of the files passed on the command line did not exist.