Man page for ?s

December 1, 2008 – 4:53 am

LS


Section: User Commands (1)
Updated: June 2006
Index
Return to Main Contents

 

NAME

ls - list directory contents
 

SYNOPSIS

ls

[OPTION]… [FILE]…
 

DESCRIPTION

List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor –sort.

Mandatory arguments to long options are mandatory for short options too.


-a, –all

do not ignore entries starting with .
-A, –almost-all

do not list implied . and ..
–author

with -l, print the author of each file
-b, –escape

print octal escapes for nongraphic characters
–block-size=SIZE

use SIZE-byte blocks
-B, –ignore-backups

do not list implied entries ending with ~
-c

with -lt: sort by, and show, ctime (time of last
modification of file status information)
with -l: show ctime and sort by name
otherwise: sort by ctime
-C

list entries by columns
–color[=WHEN]

control whether color is used to distinguish file
types. WHEN may be `never’, `always’, or `auto’
-d, –directory

list directory entries instead of contents,
and do not dereference symbolic links
-D, –dired

generate output designed for Emacs’ dired mode
-f

do not sort, enable -aU, disable -lst
-F, –classify

append indicator (one of */=>@|) to entries
–file-type

likewise, except do not append `*’
–format=WORD

across -x, commas -m, horizontal -x, long -l,
single-column -1, verbose -l, vertical -C
–full-time

like -l –time-style=full-iso
-g

like -l, but do not list owner
-G, –no-group

like -l, but do not list group
-h, –human-readable

with -l, print sizes in human readable format
(e.g., 1K 234M 2G)
–si

likewise, but use powers of 1000 not 1024
-H, –dereference-command-line

follow symbolic links listed on the command line
–dereference-command-line-symlink-to-dir

follow each command line symbolic link
that points to a directory
–hide=PATTERN

do not list implied entries matching shell PATTERN
(overridden by -a or -A)
–indicator-style=WORD append indicator with style WORD to entry names:

none (default), slash (-p),
file-type (–file-type), classify (-F)
-i, –inode

with -l, print the index number of each file
-I, –ignore=PATTERN

do not list implied entries matching shell PATTERN
-k

like –block-size=1K
-l

use a long listing format
-L, –dereference

when showing file information for a symbolic
link, show information for the file the link
references rather than for the link itself
-m

fill width with a comma separated list of entries
-n, –numeric-uid-gid

like -l, but list numeric user and group IDs
-N, –literal

print raw entry names (don’t treat e.g. control
characters specially)
-o

like -l, but do not list group information
-p, –indicator-style=slash

append / indicator to directories
-q, –hide-control-chars

print ? instead of non graphic characters
–show-control-chars

show non graphic characters as-is (default
unless program is `ls’ and output is a terminal)
-Q, –quote-name

enclose entry names in double quotes
–quoting-style=WORD

use quoting style WORD for entry names:
literal, locale, shell, shell-always, c, escape
-r, –reverse

reverse order while sorting
-R, –recursive

list subdirectories recursively
-s, –size

with -l, print size of each file, in blocks
-S

sort by file size
–sort=WORD

extension -X, none -U, size -S, time -t,
version -v, status -c, time -t, atime -u,
access -u, use -u
–time=WORD

with -l, show time as WORD instead of modification
time: atime, access, use, ctime or status; use
specified time as sort key if –sort=time
–time-style=STYLE

with -l, show times using style STYLE:
full-iso, long-iso, iso, locale, +FORMAT.
FORMAT is interpreted like `date’; if FORMAT is
FORMAT1<newline>FORMAT2, FORMAT1 applies to
non-recent files and FORMAT2 to recent files;
if STYLE is prefixed with `posix-’, STYLE
takes effect only outside the POSIX locale
-t

sort by modification time
-T, –tabsize=COLS

assume tab stops at each COLS instead of 8
-u

with -lt: sort by, and show, access time
with -l: show access time and sort by name
otherwise: sort by access time
-U

do not sort; list entries in directory order
-v

sort by version
-w, –width=COLS

assume screen width instead of current value
-x

list entries by lines instead of by columns
-X

sort alphabetically by entry extension
-1

list one file per line

SELinux options:


–lcontext

Display security context. Enable -l. Lines
will probably be too wide for most displays.
-Z, –context

Display security context so it fits on most
displays. Displays only mode, user, group,
security context and file name.
–scontext

Display only security context and file name.
–help

display this help and exit
–version

output version information and exit

SIZE may be (or may be an integer optionally followed by) one of following:
kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.

By default, color is not used to distinguish types of files. That is
equivalent to using –color=none. Using the –color option without the
optional WHEN argument is equivalent to using –color=always. With
–color=auto, color codes are output only if standard output is connected
to a terminal (tty). The environment variable LS_COLORS can influence the
colors, and can be set easily by the dircolors command.

Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.
 

AUTHOR

Written by Richard Stallman and David MacKenzie.
 

REPORTING BUGS

Report bugs to <bug-coreutils@gnu.org>.
 

COPYRIGHT

Copyright © 2006 Free Software Foundation, Inc.

This is free software. You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.
 

SEE ALSO

The full documentation for
ls

is maintained as a Texinfo manual. If the
info

and
ls

programs are properly installed at your site, the command



info ls


should give you access to the complete manual.



 

Index



NAME

SYNOPSIS

DESCRIPTION

AUTHOR

REPORTING BUGS

COPYRIGHT

SEE ALSO



Man page for ?a

September 16, 2008 – 9:44 am

CA


Section: OpenSSL (1)
Updated: 2005-07-15
Index
Return to Main Contents

 

NAME

ca - sample minimal CA application
 

SYNOPSIS


openssl ca
[-verbose]
[-config filename]
[-name section]
[-gencrl]
[-revoke file]
[-crl_reason reason]
[-crl_hold instruction]
[-crl_compromise time]
[-crl_CA_compromise time]
[-crldays days]
[-crlhours hours]
[-crlexts section]
[-startdate date]
[-enddate date]
[-days arg]
[-md arg]
[-policy arg]
[-keyfile arg]
[-key arg]
[-passin arg]
[-cert file]
[-selfsign]
[-in file]
[-out file]
[-notext]
[-outdir dir]
[-infiles]
[-spkac file]
[-ss_cert file]
[-preserveDN]
[-noemailDN]
[-batch]
[-msie_hack]
[-extensions section]
[-extfile section]
[-engine id]
[-subj arg]
[-utf8]
[-multivalue-rdn]
 

DESCRIPTION


The ca command is a minimal CA application. It can be used
to sign certificate requests in a variety of forms and generate
CRLs it also maintains a text database of issued certificates
and their status.

The options descriptions will be divided into each purpose.
 

CA OPTIONS



-config filename


specifies the configuration file to use.
-name section


specifies the configuration file section to use (overrides
default_ca in the ca section).
-in filename


an input filename containing a single certificate request to be
signed by the CA.
-ss_cert filename


a single self signed certificate to be signed by the CA.
-spkac filename


a file containing a single Netscape signed public key and challenge
and additional field values to be signed by the CA. See the SPKAC FORMAT
section for information on the required format.
-infiles


if present this should be the last option, all subsequent arguments
are assumed to the the names of files containing certificate requests.
-out filename


the output file to output certificates to. The default is standard
output. The certificate details will also be printed out to this
file.
-outdir directory


the directory to output certificates to. The certificate will be
written to a filename consisting of the serial number in hex with
“.pem” appended.
-cert


the CA certificate file.
-keyfile filename


the private key to sign requests with.
-key password


the password used to encrypt the private key. Since on some
systems the command line arguments are visible (e.g. Unix with
the ‘ps’ utility) this option should be used with caution.
-selfsign


indicates the issued certificates are to be signed with the key
the certificate requests were signed with (given with -keyfile).
Cerificate requests signed with a different key are ignored. If
-spkac, -ss_cert or -gencrl are given, -selfsign is
ignored.

A consequence of using -selfsign is that the self-signed
certificate appears among the entries in the certificate database
(see the configuration option database), and uses the same
serial number counter as all other certificates sign with the
self-signed certificate.

-passin arg


the key password source. For more information about the format of arg
see the PASS PHRASE ARGUMENTS section in openssl(1).
-verbose


this prints extra details about the operations being performed.
-notext


don’t output the text form of a certificate to the output file.
-startdate date


this allows the start date to be explicitly set. The format of the
date is YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure).
-enddate date


this allows the expiry date to be explicitly set. The format of the
date is YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure).
-days arg


the number of days to certify the certificate for.
-md alg


the message digest to use. Possible values include md5, sha1 and mdc2.
This option also applies to CRLs.
-policy arg


this option defines the CA “policy” to use. This is a section in
the configuration file which decides which fields should be mandatory
or match the CA certificate. Check out the POLICY FORMAT section
for more information.
-msie_hack


this is a legacy option to make ca work with very old versions of
the IE certificate enrollment control “certenr3”. It used UniversalStrings
for almost everything. Since the old control has various security bugs
its use is strongly discouraged. The newer control “Xenroll” does not
need this option.
-preserveDN


Normally the DN order of a certificate is the same as the order of the
fields in the relevant policy section. When this option is set the order
is the same as the request. This is largely for compatibility with the
older IE enrollment control which would only accept certificates if their
DNs match the order of the request. This is not needed for Xenroll.
-noemailDN


The DN of a certificate can contain the EMAIL field if present in the
request DN, however it is good policy just having the e-mail set into
the altName extension of the certificate. When this option is set the
EMAIL field is removed from the certificate’ subject and set only in
the, eventually present, extensions. The email_in_dn keyword can be
used in the configuration file to enable this behaviour.
-batch


this sets the batch mode. In this mode no questions will be asked
and all certificates will be certified automatically.
-extensions section


the section of the configuration file containing certificate extensions
to be added when a certificate is issued (defaults to x509_extensions
unless the -extfile option is used). If no extension section is
present then, a V1 certificate is created. If the extension section
is present (even if it is empty), then a V3 certificate is created.
-extfile file


an additional configuration file to read certificate extensions from
(using the default section unless the -extensions option is also
used).
-engine id


specifying an engine (by it’s unique id string) will cause req
to attempt to obtain a functional reference to the specified engine,
thus initialising it if needed. The engine will then be set as the default
for all available algorithms.
-subj arg


supersedes subject name given in the request.
The arg must be formatted as /type0=value0/type1=value1/type2=…,
characters may be escaped by \ (backslash), no spaces are skipped.
-utf8


this option causes field values to be interpreted as UTF8 strings, by
default they are interpreted as ASCII. This means that the field
values, whether prompted from a terminal or obtained from a
configuration file, must be valid UTF8 strings.
-multivalue-rdn


this option causes the -subj argument to be interpretedt with full
support for multivalued RDNs. Example:

/DC=org/DC=OpenSSL/DC=users/UID=123456+CN=John Doe

If -multi-rdn is not used then the UID value is 123456+CN=John Doe.


 

CRL OPTIONS



-gencrl


this option generates a CRL based on information in the index file.
-crldays num


the number of days before the next CRL is due. That is the days from
now to place in the CRL nextUpdate field.
-crlhours num


the number of hours before the next CRL is due.
-revoke filename


a filename containing a certificate to revoke.
-crl_reason reason


revocation reason, where reason is one of: unspecified, keyCompromise,
CACompromise, affiliationChanged, superseded, cessationOfOperation,
certificateHold or removeFromCRL. The matching of reason is case
insensitive. Setting any revocation reason will make the CRL v2.

In practive removeFromCRL is not particularly useful because it is only used
in delta CRLs which are not currently implemented.

-crl_hold instruction


This sets the CRL revocation reason code to certificateHold and the hold
instruction to instruction which must be an OID. Although any OID can be
used only holdInstructionNone (the use of which is discouraged by RFC2459)
holdInstructionCallIssuer or holdInstructionReject will normally be used.
-crl_compromise time


This sets the revocation reason to keyCompromise and the compromise time to
time. time should be in GeneralizedTime format that is YYYYMMDDHHMMSSZ.
-crl_CA_compromise time


This is the same as crl_compromise except the revocation reason is set to
CACompromise.
-crlexts section


the section of the configuration file containing CRL extensions to
include. If no CRL extension section is present then a V1 CRL is
created, if the CRL extension section is present (even if it is
empty) then a V2 CRL is created. The CRL extensions specified are
CRL extensions and not CRL entry extensions. It should be noted
that some software (for example Netscape) can’t handle V2 CRLs.

 

CONFIGURATION FILE OPTIONS


The section of the configuration file containing options for ca
is found as follows: If the -name command line option is used,
then it names the section to be used. Otherwise the section to
be used must be named in the default_ca option of the ca section
of the configuration file (or in the default section of the
configuration file). Besides default_ca, the following options are
read directly from the ca section:

 RANDFILE

 preserve

 msie_hack
With the exception of RANDFILE, this is probably a bug and may
change in future releases.

Many of the configuration file options are identical to command line
options. Where the option is present in the configuration file
and the command line the command line value is used. Where an
option is described as mandatory then it must be present in
the configuration file or the command line equivalent (if
any) used.


oid_file


This specifies a file containing additional OBJECT IDENTIFIERS.
Each line of the file should consist of the numerical form of the
object identifier followed by white space then the short name followed
by white space and finally the long name.
oid_section


This specifies a section in the configuration file containing extra
object identifiers. Each line should consist of the short name of the
object identifier followed by = and the numerical form. The short
and long names are the same when this option is used.
new_certs_dir


the same as the -outdir command line option. It specifies
the directory where new certificates will be placed. Mandatory.
certificate


the same as -cert. It gives the file containing the CA
certificate. Mandatory.
private_key


same as the -keyfile option. The file containing the
CA private key. Mandatory.
RANDFILE


a file used to read and write random number seed information, or
an EGD socket (see RAND_egd(3)).
default_days


the same as the -days option. The number of days to certify
a certificate for.
default_startdate


the same as the -startdate option. The start date to certify
a certificate for. If not set the current time is used.
default_enddate


the same as the -enddate option. Either this option or
default_days (or the command line equivalents) must be
present.
default_crl_hours default_crl_days


the same as the -crlhours and the -crldays options. These
will only be used if neither command line option is present. At
least one of these must be present to generate a CRL.
default_md


the same as the -md option. The message digest to use. Mandatory.
database


the text database file to use. Mandatory. This file must be present
though initially it will be empty.
unique_subject


if the value yes is given, the valid certificate entries in the
database must have unique subjects. if the value no is given,
several valid certificate entries may have the exact same subject.
The default value is yes, to be compatible with older (pre 0.9.8)
versions of OpenSSL. However, to make CA certificate roll-over easier,
it’s recommended to use the value no, especially if combined with
the -selfsign command line option.
serial


a text file containing the next serial number to use in hex. Mandatory.
This file must be present and contain a valid serial number.
crlnumber


a text file containing the next CRL number to use in hex. The crl number
will be inserted in the CRLs only if this file exists. If this file is
present, it must contain a valid CRL number.
x509_extensions


the same as -extensions.
crl_extensions


the same as -crlexts.
preserve


the same as -preserveDN
email_in_dn


the same as -noemailDN. If you want the EMAIL field to be removed
from the DN of the certificate simply set this to ‘no’. If not present
the default is to allow for the EMAIL filed in the certificate’s DN.
msie_hack


the same as -msie_hack
policy


the same as -policy. Mandatory. See the POLICY FORMAT section
for more information.
name_opt, cert_opt


these options allow the format used to display the certificate details
when asking the user to confirm signing. All the options supported by
the x509 utilities -nameopt and -certopt switches can be used
here, except the no_signame and no_sigdump are permanently set
and cannot be disabled (this is because the certificate signature cannot
be displayed because the certificate has not been signed at this point).

For convenience the values ca_default are accepted by both to produce
a reasonable output.

If neither option is present the format used in earlier versions of
OpenSSL is used. Use of the old format is strongly discouraged because
it only displays fields mentioned in the policy section, mishandles
multicharacter string types and does not display extensions.

copy_extensions


determines how extensions in certificate requests should be handled.
If set to none or this option is not present then extensions are
ignored and not copied to the certificate. If set to copy then any
extensions present in the request that are not already present are copied
to the certificate. If set to copyall then all extensions in the
request are copied to the certificate: if the extension is already present
in the certificate it is deleted first. See the WARNINGS section before
using this option.

The main use of this option is to allow a certificate request to supply
values for certain extensions such as subjectAltName.


 

POLICY FORMAT


The policy section consists of a set of variables corresponding to
certificate DN fields. If the value is “match” then the field value
must match the same field in the CA certificate. If the value is
“supplied” then it must be present. If the value is “optional” then
it may be present. Any fields not mentioned in the policy section
are silently deleted, unless the -preserveDN option is set but
this can be regarded more of a quirk than intended behaviour.
 

SPKAC FORMAT


The input to the -spkac command line option is a Netscape
signed public key and challenge. This will usually come from
the KEYGEN tag in an HTML form to create a new private key.
It is however possible to create SPKACs using the spkac utility.

The file should contain the variable SPKAC set to the value of
the SPKAC and also the required DN components as name value pairs.
If you need to include the same component twice then it can be
preceded by a number and a ‘.’.
 

EXAMPLES


Note: these examples assume that the ca directory structure is
already set up and the relevant files already exist. This usually
involves creating a CA certificate and private key with req, a
serial number file and an empty index file and placing them in
the relevant directories.

To use the sample configuration file below the directories demoCA,
demoCA/private and demoCA/newcerts would be created. The CA
certificate would be copied to demoCA/cacert.pem and its private
key to demoCA/private/cakey.pem. A file demoCA/serial would be
created containing for example “01” and the empty index file
demoCA/index.txt.

Sign a certificate request:


openssl ca -in req.pem -out newcert.pem

Sign a certificate request, using CA extensions:


openssl ca -in req.pem -extensions v3_ca -out newcert.pem

Generate a CRL


openssl ca -gencrl -out crl.pem

Sign several requests:


openssl ca -infiles req1.pem req2.pem req3.pem

Certify a Netscape SPKAC:


openssl ca -spkac spkac.txt

A sample SPKAC file (the SPKAC line has been truncated for clarity):


SPKAC=MIG0MGAwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PDhCeV/xIxUg8V70YRxK2A5
CN=Steve Test
emailAddress=steve@openssl.org
0.OU=OpenSSL Group
1.OU=Another Group

A sample configuration file with the relevant sections for ca:


[ ca ]
default_ca = CA_default # The default ca section


[ CA_default ]


dir = ./demoCA # top dir
database = $dir/index.txt # index file.
new_certs_dir = $dir/newcerts # new certs dir


certificate = $dir/cacert.pem # The CA cert
serial = $dir/serial # serial no file
private_key = $dir/private/cakey.pem# CA private key
RANDFILE = $dir/private/.rand # random number file


default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = md5 # md to use


policy = policy_any # default policy
email_in_dn = no # Don’t add the email into cert DN


name_opt = ca_default # Subject name display option
cert_opt = ca_default # Certificate display option
copy_extensions = none # Don’t copy extensions from request


[ policy_any ]
countryName = supplied
stateOrProvinceName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional

 

FILES


Note: the location of all files can change either by compile time options,
configuration file entries, environment variables or command line options.
The values below reflect the default values.


/usr/local/ssl/lib/openssl.cnf - master configuration file
./demoCA - main CA directory
./demoCA/cacert.pem - CA certificate
./demoCA/private/cakey.pem - CA private key
./demoCA/serial - CA serial number file
./demoCA/serial.old - CA serial number backup file
./demoCA/index.txt - CA text database file
./demoCA/index.txt.old - CA text database backup file
./demoCA/certs - certificate output file
./demoCA/.rnd - CA random seed information

 

ENVIRONMENT VARIABLES


OPENSSL_CONF reflects the location of master configuration file it can
be overridden by the -config command line option.
 

RESTRICTIONS


The text database index file is a critical part of the process and
if corrupted it can be difficult to fix. It is theoretically possible
to rebuild the index file from all the issued certificates and a current
CRL: however there is no option to do this.

V2 CRL features like delta CRLs are not currently supported.

Although several requests can be input and handled at once it is only
possible to include one SPKAC or self signed certificate.
 

BUGS


The use of an in memory text database can cause problems when large
numbers of certificates are present because, as the name implies
the database has to be kept in memory.

The ca command really needs rewriting or the required functionality
exposed at either a command or interface level so a more friendly utility
(perl script or GUI) can handle things properly. The scripts CA.sh and
CA.pl help a little but not very much.

Any fields in a request that are not present in a policy are silently
deleted. This does not happen if the -preserveDN option is used. To
enforce the absence of the EMAIL field within the DN, as suggested by
RFCs, regardless the contents of the request’ subject the -noemailDN
option can be used. The behaviour should be more friendly and
configurable.

Cancelling some commands by refusing to certify a certificate can
create an empty file.
 

WARNINGS


The ca command is quirky and at times downright unfriendly.

The ca utility was originally meant as an example of how to do things
in a CA. It was not supposed to be used as a full blown CA itself:
nevertheless some people are using it for this purpose.

The ca command is effectively a single user command: no locking is
done on the various files and attempts to run more than one ca command
on the same database can have unpredictable results.

The copy_extensions option should be used with caution. If care is
not taken then it can be a security risk. For example if a certificate
request contains a basicConstraints extension with CA:TRUE and the
copy_extensions value is set to copyall and the user does not spot
this when the certificate is displayed then this will hand the requestor
a valid CA certificate.

This situation can be avoided by setting copy_extensions to copy
and including basicConstraints with CA:FALSE in the configuration file.
Then if the request contains a basicConstraints extension it will be
ignored.

It is advisable to also include values for other extensions such
as keyUsage to prevent a request supplying its own values.

Additional restrictions can be placed on the CA certificate itself.
For example if the CA certificate has:


basicConstraints = CA:TRUE, pathlen:0

then even if a certificate is issued with CA:TRUE it will not be valid.
 

SEE ALSO


req(1), spkac(1), x509(1), CA.pl(1),
config(5)



 

Index



NAME

SYNOPSIS

DESCRIPTION

CA OPTIONS

CRL OPTIONS

CONFIGURATION FILE OPTIONS

POLICY FORMAT

SPKAC FORMAT

EXAMPLES

FILES

ENVIRONMENT VARIABLES

RESTRICTIONS

BUGS

WARNINGS

SEE ALSO



Man page for i?

May 14, 2008 – 7:06 am

ID


Section: User Commands (1)
Updated: May 2006
Index
Return to Main Contents

 

NAME

id - print user identity
 

SYNOPSIS

id

[OPTION]… [USERNAME]
 

DESCRIPTION

Print information for USERNAME, or the current user.


-a

ignore, for compatibility with other versions
-Z, –context

print only the security context
-g, –group

print only the effective group ID
-G, –groups

print all group IDs
-n, –name

print a name instead of a number, for -ugG
-r, –real

print the real ID instead of the effective ID, with -ugG
-u, –user

print only the effective user ID
–help

display this help and exit
–version

output version information and exit

Without any OPTION, print some useful set of identified information.
 

AUTHOR

Written by Arnold Robbins and David MacKenzie.
 

REPORTING BUGS

Report bugs to <bug-coreutils@gnu.org>.
 

COPYRIGHT

Copyright © 2006 Free Software Foundation, Inc.

This is free software. You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.
 

SEE ALSO

The full documentation for
id

is maintained as a Texinfo manual. If the
info

and
id

programs are properly installed at your site, the command



info id


should give you access to the complete manual.



 

Index



NAME

SYNOPSIS

DESCRIPTION

AUTHOR

REPORTING BUGS

COPYRIGHT

SEE ALSO



Man page for i??

May 13, 2008 – 6:55 pm

LIBIDN


Section: User Commands (1)
Updated: February 2006
Index
Return to Main Contents

 

NAME

libidn - Internationalized Domain Names command line tool
 

SYNOPSIS

libidn

[OPTIONS]… [STRINGS]…
 

DESCRIPTION

libidn 0.6.2

Command line interface to the internationalized domain name library.

All strings are expected to be encoded in the preferred charset used
by your locale. Use `–debug’ to find out what this charset is. You
can override the charset used by setting environment variable CHARSET.

To process a string that starts with `-’, for example `-foo’, use `–’
to signal the end of parameters, as in `idn –quiet -a -foo‘.


-h, –help

Print help and exit
-V, –version

Print version and exit
-s, –stringprep

Prepare string according to nameprep profile
-d, –punycode-decode

Decode Punycode
-e, –punycode-encode

Encode Punycode
-a, –idna-to-ascii

Convert to ACE according to IDNA (default)
-u, –idna-to-unicode

Convert from ACE according to IDNA
–allow-unassigned

Toggle IDNA AllowUnassigned flag (default=off)
–usestd3asciirules

Toggle IDNA UseSTD3ASCIIRules flag (default=off)
-t, –tld

Check string for TLD specific rules
Only for –idna-to-ascii and –idna-to-unicode
(default=on)
-p, –profile=STRING

Use specified stringprep profile instead
Valid stringprep profiles are `Nameprep’, `iSCSI’,
`Nodeprep’, `Resourceprep’, `trace’, and
`SASLprep’.
–debug

Print debugging information (default=off)
–quiet

Silent operation (default=off)

 

SEE ALSO

The full documentation for
libidn

is maintained as a Texinfo manual. If the
info

and
libidn

programs are properly installed at your site, the command



info libidn


should give you access to the complete manual.



 

Index



NAME

SYNOPSIS

DESCRIPTION

SEE ALSO



Man page for b?

May 13, 2008 – 1:57 am

bc


Section: User Commands (1)
Updated: .
Index
Return to Main Contents

 

NAME

bc - An arbitrary precision calculator language
 

SYNTAX

bc [ -hlwsqv ] [long-options] [ file ... ]
 

VERSION

This man page documents GNU bc version 1.06.
 

DESCRIPTION

bc is a language that supports arbitrary precision numbers
with interactive execution of statements. There are some similarities
in the syntax to the C programming language.
A standard math library is available by command line option.
If requested, the math library is defined before processing any files.
bc starts by processing code from all the files listed
on the command line in the order listed. After all files have been
processed, bc reads from the standard input. All code is
executed as it is read. (If a file contains a command to halt the
processor, bc will never read from the standard input.)

This version of bc contains several extensions beyond
traditional bc implementations and the POSIX draft standard.
Command line options can cause these extensions to print a warning
or to be rejected. This
document describes the language accepted by this processor.
Extensions will be identified as such.
 

OPTIONS


-h, –help

Print the usage and exit.
-i, –interactive

Force interactive mode.
-l, –mathlib

Define the standard math library.
-w, –warn

Give warnings for extensions to POSIX bc.
-s, –standard

Process exactly the POSIX bc language.
-q, –quiet

Do not print the normal GNU bc welcome.
-v, –version

Print the version number and copyright and quit.

 

NUMBERS

The most basic element in bc is the number. Numbers are
arbitrary precision numbers. This precision is both in the integer
part and the fractional part. All numbers are represented internally
in decimal and all computation is done in decimal. (This version
truncates results from divide and multiply operations.) There are two
attributes of numbers, the length and the scale. The length is the
total number of significant decimal digits in a number and the scale
is the total number of decimal digits after the decimal point. For
example:


.000001 has a length of 6 and scale of 6.
1935.000 has a length of 7 and a scale of 3.

 

VARIABLES

Numbers are stored in two types of variables, simple variables and
arrays. Both simple variables and array variables are named. Names
begin with a letter followed by any number of letters, digits and
underscores. All letters must be lower case. (Full alpha-numeric
names are an extension. In POSIX bc all names are a single
lower case letter.) The type of variable is clear by the context
because all array variable names will be followed by brackets ([]).

There are four special variables, scale, ibase, obase, and
last. scale defines how some operations use digits after the
decimal point. The default value of scale is 0. ibase
and obase define the conversion base for input and output
numbers. The default for both input and output is base 10.
last (an extension) is a variable that has the value of the last
printed number. These will be discussed in further detail where
appropriate. All of these variables may have values assigned to them
as well as used in expressions.
 

COMMENTS

Comments in bc start with the characters /* and end with
the characters */. Comments may start anywhere and appear as a
single space in the input. (This causes comments to delimit other
input items. For example, a comment can not be found in the middle of
a variable name.) Comments include any newlines (end of line) between
the start and the end of the comment.

To support the use of scripts for bc, a single line comment has been
added as an extension. A single line comment starts at a #
character and continues to the next end of the line. The end of line
character is not part of the comment and is processed normally.
 

EXPRESSIONS

The numbers are manipulated by expressions and statements. Since
the language was designed to be interactive, statements and expressions
are executed as soon as possible. There is no "main" program. Instead,
code is executed as it is encountered. (Functions, discussed in
detail later, are defined when encountered.)

A simple expression is just a constant. bc converts constants
into internal decimal numbers using the current input base, specified
by the variable ibase. (There is an exception in functions.)
The legal values of ibase are 2 through 16. Assigning a
value outside this range to ibase will result in a value of 2
or 16. Input numbers may contain the characters 0-9 and A-F. (Note:
They must be capitals. Lower case letters are variable names.)
Single digit numbers always have the value of the digit regardless of
the value of ibase. (i.e. A = 10.) For multi-digit numbers,
bc changes all input digits greater or equal to ibase to the
value of ibase-1. This makes the number FFF always be
the largest 3 digit number of the input base.

Full expressions are similar to many other high level languages.
Since there is only one kind of number, there are no rules for mixing
types. Instead, there are rules on the scale of expressions. Every
expression has a scale. This is derived from the scale of original
numbers, the operation performed and in many cases, the value of the
variable scale. Legal values of the variable scale are
0 to the maximum number representable by a C integer.

In the following descriptions of legal expressions, "expr" refers to a
complete expression and "var" refers to a simple or an array variable.
A simple variable is just a


name

and an array variable is specified as


name[expr]

Unless specifically
mentioned the scale of the result is the maximum scale of the
expressions involved.


- expr

The result is the negation of the expression.
++ var

The variable is incremented by one and the new value is the result of
the expression.
– var

The variable
is decremented by one and the new value is the result of the
expression.
var ++


 The result of the expression is the value of
the variable and then the variable is incremented by one.
var –

The result of the expression is the value of the variable and then
the variable is decremented by one.
expr + expr

The result of the expression is the sum of the two expressions.
expr - expr

The result of the expression is the difference of the two expressions.
expr * expr

The result of the expression is the product of the two expressions.
expr / expr

The result of the expression is the quotient of the two expressions.
The scale of the result is the value of the variable scale.
expr % expr

The result of the expression is the "remainder" and it is computed in the
following way. To compute a%b, first a/b is computed to scale
digits. That result is used to compute a-(a/b)*b to the scale of the
maximum of scale+scale(b) and scale(a). If scale is set
to zero and both expressions are integers this expression is the
integer remainder function.
expr ^ expr

The result of the expression is the value of the first raised to the
second. The second expression must be an integer. (If the second
expression is not an integer, a warning is generated and the
expression is truncated to get an integer value.) The scale of the
result is scale if the exponent is negative. If the exponent
is positive the scale of the result is the minimum of the scale of the
first expression times the value of the exponent and the maximum of
scale and the scale of the first expression. (e.g. scale(a^b)
= min(scale(a)*b, max( scale, scale(a))).) It should be noted
that expr^0 will always return the value of 1.
( expr )

This alters the standard precedence to force the evaluation of the
expression.
var = expr

The variable is assigned the value of the expression.
var <op>= expr

This is equivalent to "var = var <op> expr" with the exception that
the "var" part is evaluated only once. This can make a difference if
"var" is an array.


 Relational expressions are a special kind of expression
that always evaluate to 0 or 1, 0 if the relation is false and 1 if
the relation is true. These may appear in any legal expression.
(POSIX bc requires that relational expressions are used only in if,
while, and for statements and that only one relational test may be
done in them.) The relational operators are


expr1 < expr2

The result is 1 if expr1 is strictly less than expr2.
expr1 <= expr2

The result is 1 if expr1 is less than or equal to expr2.
expr1 > expr2

The result is 1 if expr1 is strictly greater than expr2.
expr1 >= expr2

The result is 1 if expr1 is greater than or equal to expr2.
expr1 == expr2

The result is 1 if expr1 is equal to expr2.
expr1 != expr2

The result is 1 if expr1 is not equal to expr2.

Boolean operations are also legal. (POSIX bc does NOT have
boolean operations). The result of all boolean operations are 0 and 1
(for false and true) as in relational expressions. The boolean
operators are:


!expr

The result is 1 if expr is 0.
expr && expr

The result is 1 if both expressions are non-zero.
expr || expr

The result is 1 if either expression is non-zero.

The expression precedence is as follows: (lowest to highest)


|| operator, left associative
&& operator, left associative
! operator, nonassociative
Relational operators, left associative
Assignment operator, right associative
+ and - operators, left associative
*, / and % operators, left associative
^ operator, right associative
unary - operator, nonassociative
++ and — operators, nonassociative

This precedence was chosen so that POSIX compliant bc programs
will run correctly. This will cause the use of the relational and
logical operators to have some unusual behavior when used with
assignment expressions. Consider the expression:


a = 3 < 5

Most C programmers would assume this would assign the result of "3 <
5" (the value 1) to the variable "a". What this does in bc is
assign the value 3 to the variable "a" and then compare 3 to 5. It is
best to use parenthesis when using relational and logical operators
with the assignment operators.

There are a few more special expressions that are provided in bc.
These have to do with user defined functions and standard
functions. They all appear as "name(parameters)".
See the section on functions for user defined functions. The standard
functions are:


length ( expression )

The value of the length function is the number of significant digits in the
expression.
read ( )

The read function (an extension) will read a number from the standard
input, regardless of where the function occurs. Beware, this can
cause problems with the mixing of data and program in the standard input.
The best use for this function is in a previously written program that
needs input from the user, but never allows program code to be input
from the user. The value of the read function is the number read from
the standard input using the current value of the variable
ibase for the conversion base.
scale ( expression )

The value of the scale function is the number of digits after the decimal
point in the expression.
sqrt ( expression )

The value of the sqrt function is the square root of the expression. If
the expression is negative, a run time error is generated.

 

STATEMENTS

Statements (as in most algebraic languages) provide the sequencing of
expression evaluation. In bc statements are executed "as soon
as possible." Execution happens when a newline in encountered and
there is one or more complete statements. Due to this immediate
execution, newlines are very important in bc. In fact, both a
semicolon and a newline are used as statement separators. An
improperly placed newline will cause a syntax error. Because newlines
are statement separators, it is possible to hide a newline by using
the backslash character. The sequence "\<nl>", where <nl> is the
newline appears to bc as whitespace instead of a newline. A
statement list is a series of statements separated by semicolons and
newlines. The following is a list of bc statements and what
they do: (Things enclosed in brackets ([]) are optional parts of the
statement.)


expression

This statement does one of two things. If the expression starts with
"<variable> <assignment> …", it is considered to be an assignment
statement. If the expression is not an assignment statement, the
expression is evaluated and printed to the output. After the number
is printed, a newline is printed. For example, "a=1" is an assignment
statement and "(a=1)" is an expression that has an embedded
assignment. All numbers that are printed are printed in the base
specified by the variable obase. The legal values for
obase
are 2 through BC_BASE_MAX. (See the section LIMITS.) For
bases 2 through 16, the usual method of writing numbers is used. For
bases greater than 16, bc uses a multi-character digit method
of printing the numbers where each higher base digit is printed as a
base 10 number. The multi-character digits are separated by spaces.
Each digit contains the number of characters required to represent the
base ten value of "obase-1". Since numbers are of arbitrary
precision, some numbers may not be printable on a single output line.
These long numbers will be split across lines using the "\" as the
last character on a line. The maximum number of characters printed
per line is 70. Due to the interactive nature of bc, printing
a number causes the side effect of assigning the printed value to the
special variable last. This allows the user to recover the
last value printed without having to retype the expression that
printed the number. Assigning to last is legal and will
overwrite the last printed value with the assigned value. The newly
assigned value will remain until the next number is printed or another
value is assigned to last. (Some installations may allow the
use of a single period (.) which is not part of a number as a short
hand notation for for last.)
string

The string is printed to the output. Strings start with a double quote
character and contain all characters until the next double quote character.
All characters are take literally, including any newline. No newline
character is printed after the string.
print list

The print statement (an extension) provides another method of output.
The "list" is a list of strings and expressions separated by commas.
Each string or expression is printed in the order of the list. No
terminating newline is printed. Expressions are evaluated and their
value is printed and assigned to the variable last. Strings
in the print statement are printed to the output and may contain
special characters. Special characters start with the backslash
character (\). The special characters recognized by bc are
"a" (alert or bell), "b" (backspace), "f" (form feed), "n" (newline),
"r" (carriage return), "q" (double quote), "t" (tab), and "\" (backslash).
Any other character following the backslash will be ignored.
{ statement_list }

This is the compound statement. It allows multiple statements to be
grouped together for execution.
if ( expression ) statement1 [else statement2]

The if statement evaluates the expression and executes statement1 or
statement2 depending on the value of the expression. If the expression
is non-zero, statement1 is executed. If statement2 is present and
the value of the expression is 0, then statement2 is executed. (The
else clause is an extension.)
while ( expression ) statement

The while statement will execute the statement while the expression
is non-zero. It evaluates the expression before each execution of
the statement. Termination of the loop is caused by a zero
expression value or the execution of a break statement.
for ( [expression1] ; [expression2] ; [expression3] ) statement

The for statement controls repeated execution of the statement.
Expression1 is evaluated before the loop. Expression2 is evaluated
before each execution of the statement. If it is non-zero, the statement
is evaluated. If it is zero, the loop is terminated. After each
execution of the statement, expression3 is evaluated before the reevaluation
of expression2. If expression1 or expression3 are missing, nothing is
evaluated at the point they would be evaluated.
If expression2 is missing, it is the same as substituting
the value 1 for expression2. (The optional expressions are an
extension. POSIX bc requires all three expressions.)
The following is equivalent code for the for statement:

expression1;
while (expression2) {
statement;
expression3;
}

break

This statement causes a forced exit of the most recent enclosing while
statement or for statement.
continue

The continue statement (an extension) causes the most recent enclosing
for statement to start the next iteration.
halt

The halt statement (an extension) is an executed statement that causes
the bc processor to quit only when it is executed. For example,
"if (0 == 1) halt" will not cause bc to terminate because the halt is
not executed.
return

Return the value 0 from a function. (See the section on functions.)
return ( expression )

Return the value of the expression from a function. (See the section on
functions.) As an extension, the parenthesis are not required.

 

PSEUDO STATEMENTS

These statements are not statements in the traditional sense. They are
not executed statements. Their function is performed at "compile" time.


limits

Print the local limits enforced by the local version of bc. This
is an extension.
quit

When the quit statement is read, the bc processor
is terminated, regardless of where the quit statement is found. For
example, "if (0 == 1) quit" will cause bc to terminate.
warranty

Print a longer warranty notice. This is an extension.

 

FUNCTIONS

Functions provide a method of defining a computation that can be executed
later. Functions in
bc

always compute a value and return it to the caller. Function definitions
are "dynamic" in the sense that a function is undefined until a definition
is encountered in the input. That definition is then used until another
definition function for the same name is encountered. The new definition
then replaces the older definition. A function is defined as follows:


define name ( parameters ) { newline
auto_list statement_list
}

A function call is just an expression of the form
"name(parameters)".

Parameters are numbers or arrays (an extension). In the function definition,
zero or more parameters are defined by listing their names separated by
commas. Numbers are only call by value parameters. Arrays are only
call by variable. Arrays are specified in the parameter definition by
the notation "name[]". In the function call, actual parameters
are full expressions for number parameters. The same notation is used
for passing arrays as for defining array parameters. The named array is
passed by variable to the function. Since function definitions are dynamic,
parameter numbers and types are checked when a function is called. Any
mismatch in number or types of parameters will cause a runtime error.
A runtime error will also occur for the call to an undefined function.

The auto_list is an optional list of variables that are for
"local" use. The syntax of the auto list (if present) is "auto
name, … ;". (The semicolon is optional.) Each name is
the name of an auto variable. Arrays may be specified by using the
same notation as used in parameters. These variables have their
values pushed onto a stack at the start of the function. The
variables are then initialized to zero and used throughout the
execution of the function. At function exit, these variables are
popped so that the original value (at the time of the function call)
of these variables are restored. The parameters are really auto
variables that are initialized to a value provided in the function
call. Auto variables are different than traditional local variables
because if function A calls function B, B may access function
A’s auto variables by just using the same name, unless function B has
called them auto variables. Due to the fact that auto variables and
parameters are pushed onto a stack, bc supports recursive functions.

The function body is a list of bc statements. Again, statements
are separated by semicolons or newlines. Return statements cause the
termination of a function and the return of a value. There are two
versions of the return statement. The first form, "return", returns
the value 0 to the calling expression. The second form,
"return ( expression )", computes the value of the expression
and returns that value to the calling expression. There is an implied
"return (0)" at the end of every function. This allows a function
to terminate and return 0 without an explicit return statement.

Functions also change the usage of the variable ibase. All
constants in the function body will be converted using the value of
ibase at the time of the function call. Changes of ibase
will be ignored during the execution of the function except for the
standard function read, which will always use the current value
of ibase for conversion of numbers.

As an extension, the format of the definition has been slightly relaxed.
The standard requires the opening brace be on the same line as the
define keyword and all other parts must be on following lines.
This version of bc will allow any number of newlines before and
after the opening brace of the function. For example, the following
definitions are legal.



define d (n) { return (2*n); }
define d (n)
{ return (2*n); }


 

MATH LIBRARY

If bc is invoked with the -l option, a math library is preloaded
and the default scale is set to 20. The math functions will calculate their
results to the scale set at the time of their call.
The math library defines the following functions:


s (x)

The sine of x, x is in radians.
c (x)

The cosine of x, x is in radians.
a (x)

The arctangent of x, arctangent returns radians.
l (x)

The natural logarithm of x.
e (x)

The exponential function of raising e to the value x.
j (n,x)

The bessel function of integer order n of x.

 

EXAMPLES

In /bin/sh, the following will assign the value of "pi" to the shell
variable pi.



pi=$(echo "scale=10; 4*a(1)" | bc -l)

The following is the definition of the exponential function used in the
math library. This function is written in POSIX bc.



scale = 20

/* Uses the fact that e^x = (e^(x/2))^2
When x is small enough, we use the series:
e^x = 1 + x + x^2/2! + x^3/3! + …
*/

define e(x) {
auto a, d, e, f, i, m, v, z

/* Check the sign of x. */
if (x<0) {
m = 1
x = -x
}

/* Precondition x. */
z = scale;
scale = 4 + z + .44*x;
while (x > 1) {
f += 1;
x /= 2;
}

/* Initialize the variables. */
v = 1+x
a = x
d = 1

for (i=2; 1; i++) {
e = (a *= x) / (d *= i)
if (e == 0) {
if (f>0) while (f–) v = v*v;
scale = z
if (m) return (1/v);
return (v/1);
}
v += e
}
}


The following is code that uses the extended features of bc to
implement a simple program for calculating checkbook balances. This
program is best kept in a file so that it can be used many times
without having to retype it at every use.



scale=2
print "\nCheck book program!\n"
print " Remember, deposits are negative transactions.\n"
print " Exit by a 0 transaction.\n\n"

print "Initial balance? "; bal = read()
bal /= 1
print "\n"
while (1) {
"current balance = "; bal
"transaction? "; trans = read()
if (trans == 0) break;
bal -= trans
bal /= 1
}
quit


The following is the definition of the recursive factorial function.



define f (x) {
if (x <= 1) return (1);
return (f(x-1) * x);
}


 

READLINE AND LIBEDIT OPTIONS

GNU bc can be compiled (via a configure option) to use the GNU
readline input editor library or the BSD libedit library.
This allows the user to do editing of lines before sending them
to bc. It also allows for a history of previous lines typed.
When this option is selected, bc has one more special variable.
This special variable, history is the number of lines of history
retained. For readline, a value of -1 means that an unlimited
number of history lines are retained. Setting the value of
history to a positive number restricts the number of history
lines to the number given. The value of 0 disables the history
feature. The default value is 100. For more information, read the
user manuals for the GNU readline, history and BSD libedit
libraries. One can not enable both readline and libedit
at the same time.
 

DIFFERENCES

This version of
bc

was implemented from the POSIX P1003.2/D11 draft and contains
several differences and extensions relative to the draft and
traditional implementations.
It is not implemented in the traditional way using
dc(1).

This version is a single process which parses and runs a byte code
translation of the program. There is an "undocumented" option (-c)
that causes the program to output the byte code to
the standard output instead of running it. It was mainly used for
debugging the parser and preparing the math library.

A major source of differences is
extensions, where a feature is extended to add more functionality and
additions, where new features are added.
The following is the list of differences and extensions.


LANG

This version does not conform to the POSIX standard in the processing
of the LANG environment variable and all environment variables starting
with LC_.
names

Traditional and POSIX
bc

have single letter names for functions, variables and arrays. They have
been extended to be multi-character names that start with a letter and
may contain letters, numbers and the underscore character.

Strings

Strings are not allowed to contain NUL characters. POSIX says all characters
must be included in strings.
last

POSIX bc does not have a last variable. Some implementations
of bc use the period (.) in a similar way.
comparisons

POSIX bc allows comparisons only in the if statement, the while
statement, and the second expression of the for statement. Also, only
one relational operation is allowed in each of those statements.
if statement, else clause

POSIX bc does not have an else clause.
for statement

POSIX bc requires all expressions to be present in the for statement.
&&, ||, !

POSIX bc does not have the logical operators.
read function

POSIX bc does not have a read function.
print statement

POSIX bc does not have a print statement .
continue statement

POSIX bc does not have a continue statement.
return statement

POSIX bc requires parentheses around the return expression.
array parameters

POSIX bc does not (currently) support array parameters in full.
The POSIX grammar allows for arrays in function definitions, but does
not provide a method to specify an array as an actual parameter. (This
is most likely an oversight in the grammar.) Traditional implementations
of bc have only call by value array parameters.
function format

POSIX bc requires the opening brace on the same line as the
define key word and the auto statement on the next line.
=+, =-, =*, =/, =%, =^

POSIX bc does not require these "old style" assignment operators to
be defined. This version may allow these "old style" assignments. Use
the limits statement to see if the installed version supports them. If
it does support the "old style" assignment operators, the statement
"a =- 1" will decrement a by 1 instead of setting a to the
value -1.
spaces in numbers

Other implementations of bc allow spaces in numbers. For example,
"x=1 3" would assign the value 13 to the variable x. The same statement
would cause a syntax error in this version of bc.
errors and execution

This implementation varies from other implementations in terms of what
code will be executed when syntax and other errors are found in the
program. If a syntax error is found in a function definition, error
recovery tries to find the beginning of a statement and continue to
parse the function. Once a syntax error is found in the function, the
function will not be callable and becomes undefined.
Syntax errors in the interactive execution code will invalidate the
current execution block. The execution block is terminated by an
end of line that appears after a complete sequence of statements.
For example,

a = 1
b = 2

has two execution blocks and


{ a = 1
b = 2 }

has one execution block. Any runtime error will terminate the execution
of the current execution block. A runtime warning will not terminate the
current execution block.

Interrupts

During an interactive session, the SIGINT signal (usually generated by
the control-C character from the terminal) will cause execution of the
current execution block to be interrupted. It will display a "runtime"
error indicating which function was interrupted. After all runtime
structures have been cleaned up, a message will be printed to notify the
user that bc is ready for more input. All previously defined functions
remain defined and the value of all non-auto variables are the value at
the point of interruption. All auto variables and function parameters
are removed during the
clean up process. During a non-interactive
session, the SIGINT signal will terminate the entire run of bc.

 

LIMITS

The following are the limits currently in place for this
bc

processor. Some of them may have been changed by an installation.
Use the limits statement to see the actual values.


BC_BASE_MAX

The maximum output base is currently set at 999. The maximum input base
is 16.
BC_DIM_MAX

This is currently an arbitrary limit of 65535 as distributed. Your
installation may be different.
BC_SCALE_MAX

The number of digits after the decimal point is limited to INT_MAX digits.
Also, the number of digits before the decimal point is limited to INT_MAX
digits.
BC_STRING_MAX

The limit on the number of characters in a string is INT_MAX characters.
exponent

The value of the exponent in the raise operation (^) is limited to LONG_MAX.
variable names

The current limit on the number of unique names is 32767 for each of
simple variables, arrays and functions.

 

ENVIRONMENT VARIABLES

The following environment variables are processed by bc:


POSIXLY_CORRECT

This is the same as the -s option.
BC_ENV_ARGS

This is another mechanism to get arguments to bc. The
format is the same as the command line arguments. These arguments
are processed first, so any files listed in the environent arguments
are processed before any command line argument files. This allows
the user to set up "standard" options and files to be processed
at every invocation of bc. The files in the environment
variables would typically contain function definitions for functions
the user wants defined every time bc is run.
BC_LINE_LENGTH

This should be an integer specifing the number of characters in an
output line for numbers. This includes the backslash and newline characters
for long numbers.

 

DIAGNOSTICS

If any file on the command line can not be opened, bc will report
that the file is unavailable and terminate. Also, there are compile
and run time diagnostics that should be self-explanatory.
 

BUGS

Error recovery is not very good yet.

Email bug reports to
bug-bc@gnu.org.

Be sure to include the word “bc” somewhere in the “Subject:” field.
 

AUTHOR


Philip A. Nelson
philnelson@acm.org

 

ACKNOWLEDGEMENTS

The author would like to thank Steve Sommars (Steve.Sommars@att.com) for
his extensive help in testing the implementation. Many great suggestions
were given. This is a much better product due to his involvement.



 

Index



NAME

SYNTAX

VERSION

DESCRIPTION


OPTIONS

NUMBERS

VARIABLES

COMMENTS

EXPRESSIONS

STATEMENTS

PSEUDO STATEMENTS

FUNCTIONS

MATH LIBRARY

EXAMPLES

READLINE AND LIBEDIT OPTIONS

DIFFERENCES

LIMITS


ENVIRONMENT VARIABLES

DIAGNOSTICS

BUGS

AUTHOR

ACKNOWLEDGEMENTS



Man page for id???

May 13, 2008 – 1:52 am

IDENT


Section: User Commands (1)
Updated: 1993/11/09
Index
Return to Main Contents

 

NAME

ident - identify RCS keyword strings in files
 

SYNOPSIS

ident

[
-q

] [
-V

] [
file

... ]
 

DESCRIPTION

ident

searches for all instances of the pattern
$keyword: text $

in the named files or, if no files are named, the standard input.

These patterns are normally inserted automatically by the RCS command
co(1),

but can also be inserted manually.
The option
-q

suppresses
the warning given if there are no patterns in a file.
The option
-V

prints
ident’s

version number.

ident

works on text files as well as object files and dumps.
For example, if the C program in
f.c

contains




#include <stdio.h>

static char const rcsid[] =


  "$Id: f.c,v 5.4 1993/11/09 17:40:15 eggert Exp $";

int main() { return printf("%s\n", rcsid) == EOF; }


and
f.c

is compiled into
f.o,

then the command



ident f.c f.o


will output



f.c:
$Id: f.c,v 5.4 1993/11/09 17:40:15 eggert Exp $
f.o:
$Id: f.c,v 5.4 1993/11/09 17:40:15 eggert Exp $


If a C program defines a string like
rcsid

above but does not use it,
lint(1)

may complain, and some C compilers will optimize away the string.
The most reliable solution is to have the program use the
rcsid

string, as shown in the example above.

ident

finds all instances of the
$keyword: text $

pattern, even if
keyword

is not actually an RCS-supported keyword.
This gives you information about nonstandard keywords like
$XConsortium$.

 

KEYWORDS

Here is the list of keywords currently maintained by
co(1).

All times are given in Coordinated Universal Time (UTC,
sometimes called GMT) by default, but if the files
were checked out with
co’s

-zzone

option, times are given with a numeric time zone indication appended.


$Author$


The login name of the user who checked in the revision.
$Date$


The date and time the revision was checked in.
$Header$


A standard header containing the full pathname of the RCS file, the
revision number, the date and time, the author, the state,
and the locker (if locked).
$Id$


Same as
$Header$,

except that the RCS filename is without a path.

$Locker$


The login name of the user who locked the revision (empty if not locked).
$Log$


The log message supplied during checkin.
For
ident’s

purposes, this is equivalent to
$RCSfile$.

$Name$


The symbolic name used to check out the revision, if any.
$RCSfile$


The name of the RCS file without a path.
$Revision$


The revision number assigned to the revision.
$Source$


The full pathname of the RCS file.
$State$


The state assigned to the revision with the
-s

option of
rcs(1)

or
ci(1).


co(1)

represents the following characters in keyword values by escape sequences
to keep keyword strings well-formed.


char escape sequence
tab \t
newline \n
space \040
$ \044
\ \\

 

IDENTIFICATION

Author: Walter F. Tichy.

Manual Page Revision: 5.4; Release Date: 1993/11/09.

Copyright © 1982, 1988, 1989 Walter F. Tichy.

Copyright © 1990, 1992, 1993 Paul Eggert.
 

SEE ALSO

ci(1), co(1), rcs(1), rcsdiff(1), rcsintro(1), rcsmerge(1), rlog(1),
rcsfile(5)

Walter F. Tichy,
RCS–A System for Version Control,
Software–Practice & Experience

15,

7 (July 1985), 637-654.



 

Index



NAME

SYNOPSIS

DESCRIPTION

KEYWORDS

IDENTIFICATION

SEE ALSO



Man page for id

March 24, 2008 – 5:33 am

ID


Section: User Commands (1)
Updated: May 2006
Index
Return to Main Contents

 

NAME

id - print user identity
 

SYNOPSIS

id

[OPTION]… [USERNAME]
 

DESCRIPTION

Print information for USERNAME, or the current user.


-a

ignore, for compatibility with other versions
-Z, –context

print only the security context
-g, –group

print only the effective group ID
-G, –groups

print all group IDs
-n, –name

print a name instead of a number, for -ugG
-r, –real

print the real ID instead of the effective ID, with -ugG
-u, –user

print only the effective user ID
–help

display this help and exit
–version

output version information and exit

Without any OPTION, print some useful set of identified information.
 

AUTHOR

Written by Arnold Robbins and David MacKenzie.
 

REPORTING BUGS

Report bugs to <bug-coreutils@gnu.org>.
 

COPYRIGHT

Copyright © 2006 Free Software Foundation, Inc.

This is free software. You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.
 

SEE ALSO

The full documentation for
id

is maintained as a Texinfo manual. If the
info

and
id

programs are properly installed at your site, the command



info id


should give you access to the complete manual.



 

Index



NAME

SYNOPSIS

DESCRIPTION

AUTHOR

REPORTING BUGS

COPYRIGHT

SEE ALSO



Linux: How do I find files in Linux (using locate or find)? [CentOS, RHEL, Redhat, Fedora]

March 24, 2008 – 2:03 am

There are few ways to find files in Linux. Each have their own advantages and disadvantages. Some are distribution specific and some are not installed by default. Let us start with fastest way to find files using locate and secondly we will talk about using find: a very powerful and utility which is available in almost all distributions to help users find files in Linux.

  1. locate
    • Usage: locate <what you are looking for>
    • Example: locate whois
    • Advantages: Looks through database therefore is really fast
    • Disadvantages: database has to be updated in order to find new files.
  2. find
    • Usage: find <path> –name “<what you are looking for>”
    • Example: find / –name “whois”
    • Advantages: No database to use; lots of advance features
    • Disadvantages: Can be slow; requires more typing even for simple search

Both of the above methods used for finding files in Linux can have many parameters. You can read the man page of locate or man page for find to read more ways to running the commands to find files.

Man page for b perl

February 22, 2008 – 6:17 pm

bc


Section: User Commands (1)
Updated: .
Index
Return to Main Contents

 

NAME

bc - An arbitrary precision calculator language
 

SYNTAX

bc [ -hlwsqv ] [long-options] [ file ... ]
 

VERSION

This man page documents GNU bc version 1.06.
 

DESCRIPTION

bc is a language that supports arbitrary precision numbers
with interactive execution of statements. There are some similarities
in the syntax to the C programming language.
A standard math library is available by command line option.
If requested, the math library is defined before processing any files.
bc starts by processing code from all the files listed
on the command line in the order listed. After all files have been
processed, bc reads from the standard input. All code is
executed as it is read. (If a file contains a command to halt the
processor, bc will never read from the standard input.)

This version of bc contains several extensions beyond
traditional bc implementations and the POSIX draft standard.
Command line options can cause these extensions to print a warning
or to be rejected. This
document describes the language accepted by this processor.
Extensions will be identified as such.
 

OPTIONS


-h, –help

Print the usage and exit.
-i, –interactive

Force interactive mode.
-l, –mathlib

Define the standard math library.
-w, –warn

Give warnings for extensions to POSIX bc.
-s, –standard

Process exactly the POSIX bc language.
-q, –quiet

Do not print the normal GNU bc welcome.
-v, –version

Print the version number and copyright and quit.

 

NUMBERS

The most basic element in bc is the number. Numbers are
arbitrary precision numbers. This precision is both in the integer
part and the fractional part. All numbers are represented internally
in decimal and all computation is done in decimal. (This version
truncates results from divide and multiply operations.) There are two
attributes of numbers, the length and the scale. The length is the
total number of significant decimal digits in a number and the scale
is the total number of decimal digits after the decimal point. For
example:


.000001 has a length of 6 and scale of 6.
1935.000 has a length of 7 and a scale of 3.

 

VARIABLES

Numbers are stored in two types of variables, simple variables and
arrays. Both simple variables and array variables are named. Names
begin with a letter followed by any number of letters, digits and
underscores. All letters must be lower case. (Full alpha-numeric
names are an extension. In POSIX bc all names are a single
lower case letter.) The type of variable is clear by the context
because all array variable names will be followed by brackets ([]).

There are four special variables, scale, ibase, obase, and
last. scale defines how some operations use digits after the
decimal point. The default value of scale is 0. ibase
and obase define the conversion base for input and output
numbers. The default for both input and output is base 10.
last (an extension) is a variable that has the value of the last
printed number. These will be discussed in further detail where
appropriate. All of these variables may have values assigned to them
as well as used in expressions.
 

COMMENTS

Comments in bc start with the characters /* and end with
the characters */. Comments may start anywhere and appear as a
single space in the input. (This causes comments to delimit other
input items. For example, a comment can not be found in the middle of
a variable name.) Comments include any newlines (end of line) between
the start and the end of the comment.

To support the use of scripts for bc, a single line comment has been
added as an extension. A single line comment starts at a #
character and continues to the next end of the line. The end of line
character is not part of the comment and is processed normally.
 

EXPRESSIONS

The numbers are manipulated by expressions and statements. Since
the language was designed to be interactive, statements and expressions
are executed as soon as possible. There is no "main" program. Instead,
code is executed as it is encountered. (Functions, discussed in
detail later, are defined when encountered.)

A simple expression is just a constant. bc converts constants
into internal decimal numbers using the current input base, specified
by the variable ibase. (There is an exception in functions.)
The legal values of ibase are 2 through 16. Assigning a
value outside this range to ibase will result in a value of 2
or 16. Input numbers may contain the characters 0-9 and A-F. (Note:
They must be capitals. Lower case letters are variable names.)
Single digit numbers always have the value of the digit regardless of
the value of ibase. (i.e. A = 10.) For multi-digit numbers,
bc changes all input digits greater or equal to ibase to the
value of ibase-1. This makes the number FFF always be
the largest 3 digit number of the input base.

Full expressions are similar to many other high level languages.
Since there is only one kind of number, there are no rules for mixing
types. Instead, there are rules on the scale of expressions. Every
expression has a scale. This is derived from the scale of original
numbers, the operation performed and in many cases, the value of the
variable scale. Legal values of the variable scale are
0 to the maximum number representable by a C integer.

In the following descriptions of legal expressions, "expr" refers to a
complete expression and "var" refers to a simple or an array variable.
A simple variable is just a


name

and an array variable is specified as


name[expr]

Unless specifically
mentioned the scale of the result is the maximum scale of the
expressions involved.


- expr

The result is the negation of the expression.
++ var

The variable is incremented by one and the new value is the result of
the expression.
– var

The variable
is decremented by one and the new value is the result of the
expression.
var ++


 The result of the expression is the value of
the variable and then the variable is incremented by one.
var –

The result of the expression is the value of the variable and then
the variable is decremented by one.
expr + expr

The result of the expression is the sum of the two expressions.
expr - expr

The result of the expression is the difference of the two expressions.
expr * expr

The result of the expression is the product of the two expressions.
expr / expr

The result of the expression is the quotient of the two expressions.
The scale of the result is the value of the variable scale.
expr % expr

The result of the expression is the "remainder" and it is computed in the
following way. To compute a%b, first a/b is computed to scale
digits. That result is used to compute a-(a/b)*b to the scale of the
maximum of scale+scale(b) and scale(a). If scale is set
to zero and both expressions are integers this expression is the
integer remainder function.
expr ^ expr

The result of the expression is the value of the first raised to the
second. The second expression must be an integer. (If the second
expression is not an integer, a warning is generated and the
expression is truncated to get an integer value.) The scale of the
result is scale if the exponent is negative. If the exponent
is positive the scale of the result is the minimum of the scale of the
first expression times the value of the exponent and the maximum of
scale and the scale of the first expression. (e.g. scale(a^b)
= min(scale(a)*b, max( scale, scale(a))).) It should be noted
that expr^0 will always return the value of 1.
( expr )

This alters the standard precedence to force the evaluation of the
expression.
var = expr

The variable is assigned the value of the expression.
var <op>= expr

This is equivalent to "var = var <op> expr" with the exception that
the "var" part is evaluated only once. This can make a difference if
"var" is an array.


 Relational expressions are a special kind of expression
that always evaluate to 0 or 1, 0 if the relation is false and 1 if
the relation is true. These may appear in any legal expression.
(POSIX bc requires that relational expressions are used only in if,
while, and for statements and that only one relational test may be
done in them.) The relational operators are


expr1 < expr2

The result is 1 if expr1 is strictly less than expr2.
expr1 <= expr2

The result is 1 if expr1 is less than or equal to expr2.
expr1 > expr2

The result is 1 if expr1 is strictly greater than expr2.
expr1 >= expr2

The result is 1 if expr1 is greater than or equal to expr2.
expr1 == expr2

The result is 1 if expr1 is equal to expr2.
expr1 != expr2

The result is 1 if expr1 is not equal to expr2.

Boolean operations are also legal. (POSIX bc does NOT have
boolean operations). The result of all boolean operations are 0 and 1
(for false and true) as in relational expressions. The boolean
operators are:


!expr

The result is 1 if expr is 0.
expr && expr

The result is 1 if both expressions are non-zero.
expr || expr

The result is 1 if either expression is non-zero.

The expression precedence is as follows: (lowest to highest)


|| operator, left associative
&& operator, left associative
! operator, nonassociative
Relational operators, left associative
Assignment operator, right associative
+ and - operators, left associative
*, / and % operators, left associative
^ operator, right associative
unary - operator, nonassociative
++ and — operators, nonassociative

This precedence was chosen so that POSIX compliant bc programs
will run correctly. This will cause the use of the relational and
logical operators to have some unusual behavior when used with
assignment expressions. Consider the expression:


a = 3 < 5

Most C programmers would assume this would assign the result of "3 <
5" (the value 1) to the variable "a". What this does in bc is
assign the value 3 to the variable "a" and then compare 3 to 5. It is
best to use parenthesis when using relational and logical operators
with the assignment operators.

There are a few more special expressions that are provided in bc.
These have to do with user defined functions and standard
functions. They all appear as "name(parameters)".
See the section on functions for user defined functions. The standard
functions are:


length ( expression )

The value of the length function is the number of significant digits in the
expression.
read ( )

The read function (an extension) will read a number from the standard
input, regardless of where the function occurs. Beware, this can
cause problems with the mixing of data and program in the standard input.
The best use for this function is in a previously written program that
needs input from the user, but never allows program code to be input
from the user. The value of the read function is the number read from
the standard input using the current value of the variable
ibase for the conversion base.
scale ( expression )

The value of the scale function is the number of digits after the decimal
point in the expression.
sqrt ( expression )

The value of the sqrt function is the square root of the expression. If
the expression is negative, a run time error is generated.

 

STATEMENTS

Statements (as in most algebraic languages) provide the sequencing of
expression evaluation. In bc statements are executed "as soon
as possible." Execution happens when a newline in encountered and
there is one or more complete statements. Due to this immediate
execution, newlines are very important in bc. In fact, both a
semicolon and a newline are used as statement separators. An
improperly placed newline will cause a syntax error. Because newlines
are statement separators, it is possible to hide a newline by using
the backslash character. The sequence "<nl>", where <nl> is the
newline appears to bc as whitespace instead of a newline. A
statement list is a series of statements separated by semicolons and
newlines. The following is a list of bc statements and what
they do: (Things enclosed in brackets ([]) are optional parts of the
statement.)


expression

This statement does one of two things. If the expression starts with
"<variable> <assignment> …", it is considered to be an assignment
statement. If the expression is not an assignment statement, the
expression is evaluated and printed to the output. After the number
is printed, a newline is printed. For example, "a=1" is an assignment
statement and "(a=1)" is an expression that has an embedded
assignment. All numbers that are printed are printed in the base
specified by the variable obase. The legal values for
obase
are 2 through BC_BASE_MAX. (See the section LIMITS.) For
bases 2 through 16, the usual method of writing numbers is used. For
bases greater than 16, bc uses a multi-character digit method
of printing the numbers where each higher base digit is printed as a
base 10 number. The multi-character digits are separated by spaces.
Each digit contains the number of characters required to represent the
base ten value of "obase-1". Since numbers are of arbitrary
precision, some numbers may not be printable on a single output line.
These long numbers will be split across lines using the "" as the
last character on a line. The maximum number of characters printed
per line is 70. Due to the interactive nature of bc, printing
a number causes the side effect of assigning the printed value to the
special variable last. This allows the user to recover the
last value printed without having to retype the expression that
printed the number. Assigning to last is legal and will
overwrite the last printed value with the assigned value. The newly
assigned value will remain until the next number is printed or another
value is assigned to last. (Some installations may allow the
use of a single period (.) which is not part of a number as a short
hand notation for for last.)
string

The string is printed to the output. Strings start with a double quote
character and contain all characters until the next double quote character.
All characters are take literally, including any newline. No newline
character is printed after the string.
print list

The print statement (an extension) provides another method of output.
The "list" is a list of strings and expressions separated by commas.
Each string or expression is printed in the order of the list. No
terminating newline is printed. Expressions are evaluated and their
value is printed and assigned to the variable last. Strings
in the print statement are printed to the output and may contain
special characters. Special characters start with the backslash
character (). The special characters recognized by bc are
"a" (alert or bell), "b" (backspace), "f" (form feed), "n" (newline),
"r" (carriage return), "q" (double quote), "t" (tab), and "" (backslash).
Any other character following the backslash will be ignored.
{ statement_list }

This is the compound statement. It allows multiple statements to be
grouped together for execution.
if ( expression ) statement1 [else statement2]

The if statement evaluates the expression and executes statement1 or
statement2 depending on the value of the expression. If the expression
is non-zero, statement1 is executed. If statement2 is present and
the value of the expression is 0, then statement2 is executed. (The
else clause is an extension.)
while ( expression ) statement

The while statement will execute the statement while the expression
is non-zero. It evaluates the expression before each execution of
the statement. Termination of the loop is caused by a zero
expression value or the execution of a break statement.
for ( [expression1] ; [expression2] ; [expression3] ) statement

The for statement controls repeated execution of the statement.
Expression1 is evaluated before the loop. Expression2 is evaluated
before each execution of the statement. If it is non-zero, the statement
is evaluated. If it is zero, the loop is terminated. After each
execution of the statement, expression3 is evaluated before the reevaluation
of expression2. If expression1 or expression3 are missing, nothing is
evaluated at the point they would be evaluated.
If expression2 is missing, it is the same as substituting
the value 1 for expression2. (The optional expressions are an
extension. POSIX bc requires all three expressions.)
The following is equivalent code for the for statement:

expression1;
while (expression2) {
statement;
expression3;
}

break

This statement causes a forced exit of the most recent enclosing while
statement or for statement.
continue

The continue statement (an extension) causes the most recent enclosing
for statement to start the next iteration.
halt

The halt statement (an extension) is an executed statement that causes
the bc processor to quit only when it is executed. For example,
"if (0 == 1) halt" will not cause bc to terminate because the halt is
not executed.
return

Return the value 0 from a function. (See the section on functions.)
return ( expression )

Return the value of the expression from a function. (See the section on
functions.) As an extension, the parenthesis are not required.

 

PSEUDO STATEMENTS

These statements are not statements in the traditional sense. They are
not executed statements. Their function is performed at "compile" time.


limits

Print the local limits enforced by the local version of bc. This
is an extension.
quit

When the quit statement is read, the bc processor
is terminated, regardless of where the quit statement is found. For
example, "if (0 == 1) quit" will cause bc to terminate.
warranty

Print a longer warranty notice. This is an extension.

 

FUNCTIONS

Functions provide a method of defining a computation that can be executed
later. Functions in
bc

always compute a value and return it to the caller. Function definitions
are "dynamic" in the sense that a function is undefined until a definition
is encountered in the input. That definition is then used until another
definition function for the same name is encountered. The new definition
then replaces the older definition. A function is defined as follows:


define name ( parameters ) { newline
auto_list statement_list
}

A function call is just an expression of the form
"name(parameters)".

Parameters are numbers or arrays (an extension). In the function definition,
zero or more parameters are defined by listing their names separated by
commas. Numbers are only call by value parameters. Arrays are only
call by variable. Arrays are specified in the parameter definition by
the notation "name[]". In the function call, actual parameters
are full expressions for number parameters. The same notation is used
for passing arrays as for defining array parameters. The named array is
passed by variable to the function. Since function definitions are dynamic,
parameter numbers and types are checked when a function is called. Any
mismatch in number or types of parameters will cause a runtime error.
A runtime error will also occur for the call to an undefined function.

The auto_list is an optional list of variables that are for
"local" use. The syntax of the auto list (if present) is "auto
name, … ;". (The semicolon is optional.) Each name is
the name of an auto variable. Arrays may be specified by using the
same notation as used in parameters. These variables have their
values pushed onto a stack at the start of the function. The
variables are then initialized to zero and used throughout the
execution of the function. At function exit, these variables are
popped so that the original value (at the time of the function call)
of these variables are restored. The parameters are really auto
variables that are initialized to a value provided in the function
call. Auto variables are different than traditional local variables
because if function A calls function B, B may access function
A’s auto variables by just using the same name, unless function B has
called them auto variables. Due to the fact that auto variables and
parameters are pushed onto a stack, bc supports recursive functions.

The function body is a list of bc statements. Again, statements
are separated by semicolons or newlines. Return statements cause the
termination of a function and the return of a value. There are two
versions of the return statement. The first form, "return", returns
the value 0 to the calling expression. The second form,
"return ( expression )", computes the value of the expression
and returns that value to the calling expression. There is an implied
"return (0)" at the end of every function. This allows a function
to terminate and return 0 without an explicit return statement.

Functions also change the usage of the variable ibase. All
constants in the function body will be converted using the value of
ibase at the time of the function call. Changes of ibase
will be ignored during the execution of the function except for the
standard function read, which will always use the current value
of ibase for conversion of numbers.

As an extension, the format of the definition has been slightly relaxed.
The standard requires the opening brace be on the same line as the
define keyword and all other parts must be on following lines.
This version of bc will allow any number of newlines before and
after the opening brace of the function. For example, the following
definitions are legal.



define d (n) { return (2*n); }
define d (n)
{ return (2*n); }


 

MATH LIBRARY

If bc is invoked with the -l option, a math library is preloaded
and the default scale is set to 20. The math functions will calculate their
results to the scale set at the time of their call.
The math library defines the following functions:


s (x)

The sine of x, x is in radians.
c (x)

The cosine of x, x is in radians.
a (x)

The arctangent of x, arctangent returns radians.
l (x)

The natural logarithm of x.
e (x)

The exponential function of raising e to the value x.
j (n,x)

The bessel function of integer order n of x.

 

EXAMPLES

In /bin/sh, the following will assign the value of "pi" to the shell
variable pi.



pi=$(echo "scale=10; 4*a(1)" | bc -l)

The following is the definition of the exponential function used in the
math library. This function is written in POSIX bc.



scale = 20

/* Uses the fact that e^x = (e^(x/2))^2
When x is small enough, we use the series:
e^x = 1 + x + x^2/2! + x^3/3! + …
*/

define e(x) {
auto a, d, e, f, i, m, v, z

/* Check the sign of x. */
if (x<0) {
m = 1
x = -x
}

/* Precondition x. */
z = scale;
scale = 4 + z + .44*x;
while (x > 1) {
f += 1;
x /= 2;
}

/* Initialize the variables. */
v = 1+x
a = x
d = 1

for (i=2; 1; i++) {
e = (a *= x) / (d *= i)
if (e == 0) {
if (f>0) while (f–) v = v*v;
scale = z
if (m) return (1/v);
return (v/1);
}
v += e
}
}


The following is code that uses the extended features of bc to
implement a simple program for calculating checkbook balances. This
program is best kept in a file so that it can be used many times
without having to retype it at every use.



scale=2
print "nCheck book program!n"
print " Remember, deposits are negative transactions.n"
print " Exit by a 0 transaction.nn"

print "Initial balance? "; bal = read()
bal /= 1
print "n"
while (1) {
"current balance = "; bal
"transaction? "; trans = read()
if (trans == 0) break;
bal -= trans
bal /= 1
}
quit


The following is the definition of the recursive factorial function.



define f (x) {
if (x <= 1) return (1);
return (f(x-1) * x);
}


 

READLINE AND LIBEDIT OPTIONS

GNU bc can be compiled (via a configure option) to use the GNU
readline input editor library or the BSD libedit library.
This allows the user to do editing of lines before sending them
to bc. It also allows for a history of previous lines typed.
When this option is selected, bc has one more special variable.
This special variable, history is the number of lines of history
retained. For readline, a value of -1 means that an unlimited
number of history lines are retained. Setting the value of
history to a positive number restricts the number of history
lines to the number given. The value of 0 disables the history
feature. The default value is 100. For more information, read the
user manuals for the GNU readline, history and BSD libedit
libraries. One can not enable both readline and libedit
at the same time.
 

DIFFERENCES

This version of
bc

was implemented from the POSIX P1003.2/D11 draft and contains
several differences and extensions relative to the draft and
traditional implementations.
It is not implemented in the traditional way using
dc(1).

This version is a single process which parses and runs a byte code
translation of the program. There is an "undocumented" option (-c)
that causes the program to output the byte code to
the standard output instead of running it. It was mainly used for
debugging the parser and preparing the math library.

A major source of differences is
extensions, where a feature is extended to add more functionality and
additions, where new features are added.
The following is the list of differences and extensions.


LANG

This version does not conform to the POSIX standard in the processing
of the LANG environment variable and all environment variables starting
with LC_.
names

Traditional and POSIX
bc

have single letter names for functions, variables and arrays. They have
been extended to be multi-character names that start with a letter and
may contain letters, numbers and the underscore character.

Strings

Strings are not allowed to contain NUL characters. POSIX says all characters
must be included in strings.
last

POSIX bc does not have a last variable. Some implementations
of bc use the period (.) in a similar way.
comparisons

POSIX bc allows comparisons only in the if statement, the while
statement, and the second expression of the for statement. Also, only
one relational operation is allowed in each of those statements.
if statement, else clause

POSIX bc does not have an else clause.
for statement

POSIX bc requires all expressions to be present in the for statement.
&&, ||, !

POSIX bc does not have the logical operators.
read function

POSIX bc does not have a read function.
print statement

POSIX bc does not have a print statement .
continue statement

POSIX bc does not have a continue statement.
return statement

POSIX bc requires parentheses around the return expression.
array parameters

POSIX bc does not (currently) support array parameters in full.
The POSIX grammar allows for arrays in function definitions, but does
not provide a method to specify an array as an actual parameter. (This
is most likely an oversight in the grammar.) Traditional implementations
of bc have only call by value array parameters.
function format

POSIX bc requires the opening brace on the same line as the
define key word and the auto statement on the next line.
=+, =-, =*, =/, =%, =^

POSIX bc does not require these "old style" assignment operators to
be defined. This version may allow these "old style" assignments. Use
the limits statement to see if the installed version supports them. If
it does support the "old style" assignment operators, the statement
"a =- 1" will decrement a by 1 instead of setting a to the
value -1.
spaces in numbers

Other implementations of bc allow spaces in numbers. For example,
"x=1 3" would assign the value 13 to the variable x. The same statement
would cause a syntax error in this version of bc.
errors and execution

This implementation varies from other implementations in terms of what
code will be executed when syntax and other errors are found in the
program. If a syntax error is found in a function definition, error
recovery tries to find the beginning of a statement and continue to
parse the function. Once a syntax error is found in the function, the
function will not be callable and becomes undefined.
Syntax errors in the interactive execution code will invalidate the
current execution block. The execution block is terminated by an
end of line that appears after a complete sequence of statements.
For example,

a = 1
b = 2

has two execution blocks and


{ a = 1
b = 2 }

has one execution block. Any runtime error will terminate the execution
of the current execution block. A runtime warning will not terminate the
current execution block.

Interrupts

During an interactive session, the SIGINT signal (usually generated by
the control-C character from the terminal) will cause execution of the
current execution block to be interrupted. It will display a "runtime"
error indicating which function was interrupted. After all runtime
structures have been cleaned up, a message will be printed to notify the
user that bc is ready for more input. All previously defined functions
remain defined and the value of all non-auto variables are the value at
the point of interruption. All auto variables and function parameters
are removed during the
clean up process. During a non-interactive
session, the SIGINT signal will terminate the entire run of bc.

 

LIMITS

The following are the limits currently in place for this
bc

processor. Some of them may have been changed by an installation.
Use the limits statement to see the actual values.


BC_BASE_MAX

The maximum output base is currently set at 999. The maximum input base
is 16.
BC_DIM_MAX

This is currently an arbitrary limit of 65535 as distributed. Your
installation may be different.
BC_SCALE_MAX

The number of digits after the decimal point is limited to INT_MAX digits.
Also, the number of digits before the decimal point is limited to INT_MAX
digits.
BC_STRING_MAX

The limit on the number of characters in a string is INT_MAX characters.
exponent

The value of the exponent in the raise operation (^) is limited to LONG_MAX.
variable names

The current limit on the number of unique names is 32767 for each of
simple variables, arrays and functions.

 

ENVIRONMENT VARIABLES

The following environment variables are processed by bc:


POSIXLY_CORRECT

This is the same as the -s option.
BC_ENV_ARGS

This is another mechanism to get arguments to bc. The
format is the same as the command line arguments. These arguments
are processed first, so any files listed in the environent arguments
are processed before any command line argument files. This allows
the user to set up "standard" options and files to be processed
at every invocation of bc. The files in the environment
variables would typically contain function definitions for functions
the user wants defined every time bc is run.
BC_LINE_LENGTH

This should be an integer specifing the number of characters in an
output line for numbers. This includes the backslash and newline characters
for long numbers.

 

DIAGNOSTICS

If any file on the command line can not be opened, bc will report
that the file is unavailable and terminate. Also, there are compile
and run time diagnostics that should be self-explanatory.
 

BUGS

Error recovery is not very good yet.

Email bug reports to
bug-bc@gnu.org.

Be sure to include the word “bc” somewhere in the “Subject:” field.
 

AUTHOR


Philip A. Nelson
philnelson@acm.org

 

ACKNOWLEDGEMENTS

The author would like to thank Steve Sommars (Steve.Sommars@att.com) for
his extensive help in testing the implementation. Many great suggestions
were given. This is a much better product due to his involvement.



 

Index



NAME

SYNTAX

VERSION

DESCRIPTION


OPTIONS

NUMBERS

VARIABLES

COMMENTS

EXPRESSIONS

STATEMENTS

PSEUDO STATEMENTS

FUNCTIONS

MATH LIBRARY

EXAMPLES

READLINE AND LIBEDIT OPTIONS

DIFFERENCES

LIMITS


ENVIRONMENT VARIABLES

DIAGNOSTICS

BUGS

AUTHOR

ACKNOWLEDGEMENTS



Man page for bc

January 21, 2008 – 4:39 pm

bc

Section: User Commands (1)
Updated: .
Index
Return to Main Contents


NAME

bc - An arbitrary precision calculator language

SYNTAX

bc [ -hlwsqv ] [long-options] [ file ... ]

VERSION

This man page documents GNU bc version 1.06.

DESCRIPTION

bc is a language that supports arbitrary precision numbers
with interactive execution of statements. There are some similarities
in the syntax to the C programming language.
A standard math library is available by command line option.
If requested, the math library is defined before processing any files.
bc starts by processing code from all the files listed
on the command line in the order listed. After all files have been
processed, bc reads from the standard input. All code is
executed as it is read. (If a file contains a command to halt the
processor, bc will never read from the standard input.)

This version of bc contains several extensions beyond
traditional bc implementations and the POSIX draft standard.
Command line options can cause these extensions to print a warning
or to be rejected. This
document describes the language accepted by this processor.
Extensions will be identified as such.

OPTIONS

-h, –help
Print the usage and exit.
-i, –interactive
Force interactive mode.
-l, –mathlib
Define the standard math library.
-w, –warn
Give warnings for extensions to POSIX bc.
-s, –standard
Process exactly the POSIX bc language.
-q, –quiet
Do not print the normal GNU bc welcome.
-v, –version
Print the version number and copyright and quit.

NUMBERS

The most basic element in bc is the number. Numbers are
arbitrary precision numbers. This precision is both in the integer
part and the fractional part. All numbers are represented internally
in decimal and all computation is done in decimal. (This version
truncates results from divide and multiply operations.) There are two
attributes of numbers, the length and the scale. The length is the
total number of significant decimal digits in a number and the scale
is the total number of decimal digits after the decimal point. For
example:

.000001 has a length of 6 and scale of 6. 1935.000 has a length of 7 and a scale of 3.

VARIABLES

Numbers are stored in two types of variables, simple variables and
arrays. Both simple variables and array variables are named. Names
begin with a letter followed by any number of letters, digits and
underscores. All letters must be lower case. (Full alpha-numeric
names are an extension. In POSIX bc all names are a single
lower case letter.) The type of variable is clear by the context
because all array variable names will be followed by brackets ([]).

There are four special variables, scale, ibase, obase, and
last. scale defines how some operations use digits after the
decimal point. The default value of scale is 0. ibase
and obase define the conversion base for input and output
numbers. The default for both input and output is base 10.
last (an extension) is a variable that has the value of the last
printed number. These will be discussed in further detail where
appropriate. All of these variables may have values assigned to them
as well as used in expressions.

COMMENTS

Comments in bc start with the characters /* and end with
the characters */. Comments may start anywhere and appear as a
single space in the input. (This causes comments to delimit other
input items. For example, a comment can not be found in the middle of
a variable name.) Comments include any newlines (end of line) between
the start and the end of the comment.

To support the use of scripts for bc, a single line comment has been
added as an extension. A single line comment starts at a #
character and continues to the next end of the line. The end of line
character is not part of the comment and is processed normally.

EXPRESSIONS

The numbers are manipulated by expressions and statements. Since
the language was designed to be interactive, statements and expressions
are executed as soon as possible. There is no “main” program. Instead,
code is executed as it is encountered. (Functions, discussed in
detail later, are defined when encountered.)

A simple expression is just a constant. bc converts constants
into internal decimal numbers using the current input base, specified
by the variable ibase. (There is an exception in functions.)
The legal values of ibase are 2 through 16. Assigning a
value outside this range to ibase will result in a value of 2
or 16. Input numbers may contain the characters 0-9 and A-F. (Note:
They must be capitals. Lower case letters are variable names.)
Single digit numbers always have the value of the digit regardless of
the value of ibase. (i.e. A = 10.) For multi-digit numbers,
bc changes all input digits greater or equal to ibase to the
value of ibase-1. This makes the number FFF always be
the largest 3 digit number of the input base.

Full expressions are similar to many other high level languages.
Since there is only one kind of number, there are no rules for mixing
types. Instead, there are rules on the scale of expressions. Every
expression has a scale. This is derived from the scale of original
numbers, the operation performed and in many cases, the value of the
variable scale. Legal values of the variable scale are
0 to the maximum number representable by a C integer.

In the following descriptions of legal expressions, “expr” refers to a
complete expression and “var” refers to a simple or an array variable.
A simple variable is just a

name

and an array variable is specified as

name[expr]

Unless specifically
mentioned the scale of the result is the maximum scale of the
expressions involved.

- expr
The result is the negation of the expression.
++ var
The variable is incremented by one and the new value is the result of
the expression.
– var
The variable
is decremented by one and the new value is the result of the
expression.
var ++
The result of the expression is the value of
the variable and then the variable is incremented by one.

var –
The result of the expression is the value of the variable and then
the variable is decremented by one.
expr + expr
The result of the expression is the sum of the two expressions.
expr - expr
The result of the expression is the difference of the two expressions.
expr * expr
The result of the expression is the product of the two expressions.
expr / expr
The result of the expression is the quotient of the two expressions.
The scale of the result is the value of the variable scale.
expr % expr
The result of the expression is the “remainder” and it is computed in the
following way. To compute a%b, first a/b is computed to scale
digits. That result is used to compute a-(a/b)*b to the scale of the
maximum of scale+scale(b) and scale(a). If scale is set
to zero and both expressions are integers this expression is the
integer remainder function.
expr ^ expr
The result of the expression is the value of the first raised to the
second. The second expression must be an integer. (If the second
expression is not an integer, a warning is generated and the
expression is truncated to get an integer value.) The scale of the
result is scale if the exponent is negative. If the exponent
is positive the scale of the result is the minimum of the scale of the
first expression times the value of the exponent and the maximum of
scale and the scale of the first expression. (e.g. scale(a^b)
= min(scale(a)*b, max( scale, scale(a))).) It should be noted
that expr^0 will always return the value of 1.
( expr )
This alters the standard precedence to force the evaluation of the
expression.
var = expr
The variable is assigned the value of the expression.
var <op>= expr
This is equivalent to “var = var <op> expr” with the exception that
the “var” part is evaluated only once. This can make a difference if
“var” is an array.

Relational expressions are a special kind of expression
that always evaluate to 0 or 1, 0 if the relation is false and 1 if
the relation is true. These may appear in any legal expression.
(POSIX bc requires that relational expressions are used only in if,
while, and for statements and that only one relational test may be
done in them.) The relational operators are

expr1 < expr2
The result is 1 if expr1 is strictly less than expr2.
expr1 <= expr2
The result is 1 if expr1 is less than or equal to expr2.
expr1 > expr2
The result is 1 if expr1 is strictly greater than expr2.
expr1 >= expr2
The result is 1 if expr1 is greater than or equal to expr2.
expr1 == expr2
The result is 1 if expr1 is equal to expr2.
expr1 != expr2
The result is 1 if expr1 is not equal to expr2.

Boolean operations are also legal. (POSIX bc does NOT have
boolean operations). The result of all boolean operations are 0 and 1
(for false and true) as in relational expressions. The boolean
operators are:

!expr
The result is 1 if expr is 0.
expr && expr
The result is 1 if both expressions are non-zero.
expr || expr
The result is 1 if either expression is non-zero.

The expression precedence is as follows: (lowest to highest)

|| operator, left associative && operator, left associative ! operator, nonassociative Relational operators, left associative Assignment operator, right associative + and - operators, left associative *, / and % operators, left associative ^ operator, right associative unary - operator, nonassociative ++ and -- operators, nonassociative

This precedence was chosen so that POSIX compliant bc programs
will run correctly. This will cause the use of the relational and
logical operators to have some unusual behavior when used with
assignment expressions. Consider the expression:

a = 3 < 5

Most C programmers would assume this would assign the result of “3 <
5″ (the value 1) to the variable “a”. What this does in bc is
assign the value 3 to the variable “a” and then compare 3 to 5. It is
best to use parenthesis when using relational and logical operators
with the assignment operators.

There are a few more special expressions that are provided in bc.
These have to do with user defined functions and standard
functions. They all appear as “name(parameters)“.
See the section on functions for user defined functions. The standard
functions are:

length ( expression )
The value of the length function is the number of significant digits in the
expression.
read ( )
The read function (an extension) will read a number from the standard
input, regardless of where the function occurs. Beware, this can
cause problems with the mixing of data and program in the standard input.
The best use for this function is in a previously written program that
needs input from the user, but never allows program code to be input
from the user. The value of the read function is the number read from
the standard input using the current value of the variable
ibase for the conversion base.
scale ( expression )
The value of the scale function is the number of digits after the decimal
point in the expression.
sqrt ( expression )
The value of the sqrt function is the square root of the expression. If
the expression is negative, a run time error is generated.

STATEMENTS

Statements (as in most algebraic languages) provide the sequencing of
expression evaluation. In bc statements are executed “as soon
as possible.” Execution happens when a newline in encountered and
there is one or more complete statements. Due to this immediate
execution, newlines are very important in bc. In fact, both a
semicolon and a newline are used as statement separators. An
improperly placed newline will cause a syntax error. Because newlines
are statement separators, it is possible to hide a newline by using
the backslash character. The sequence “\<nl>”, where <nl> is the
newline appears to bc as whitespace instead of a newline. A
statement list is a series of statements separated by semicolons and
newlines. The following is a list of bc statements and what
they do: (Things enclosed in brackets ([]) are optional parts of the
statement.)

expression
This statement does one of two things. If the expression starts with
“<variable> <assignment> …”, it is considered to be an assignment
statement. If the expression is not an assignment statement, the
expression is evaluated and printed to the output. After the number
is printed, a newline is printed. For example, “a=1″ is an assignment
statement and “(a=1)” is an expression that has an embedded
assignment. All numbers that are printed are printed in the base
specified by the variable obase. The legal values for
obase
are 2 through BC_BASE_MAX. (See the section LIMITS.) For
bases 2 through 16, the usual method of writing numbers is used. For
bases greater than 16, bc uses a multi-character digit method
of printing the numbers where each higher base digit is printed as a
base 10 number. The multi-character digits are separated by spaces.
Each digit contains the number of characters required to represent the
base ten value of “obase-1″. Since numbers are of arbitrary
precision, some numbers may not be printable on a single output line.
These long numbers will be split across lines using the “\” as the
last character on a line. The maximum number of characters printed
per line is 70. Due to the interactive nature of bc, printing
a number causes the side effect of assigning the printed value to the
special variable last. This allows the user to recover the
last value printed without having to retype the expression that
printed the number. Assigning to last is legal and will
overwrite the last printed value with the assigned value. The newly
assigned value will remain until the next number is printed or another
value is assigned to last. (Some installations may allow the
use of a single period (.) which is not part of a number as a short
hand notation for for last.)
string
The string is printed to the output. Strings start with a double quote
character and contain all characters until the next double quote character.
All characters are take literally, including any newline. No newline
character is printed after the string.
print list
The print statement (an extension) provides another method of output.
The “list” is a list of strings and expressions separated by commas.
Each string or expression is printed in the order of the list. No
terminating newline is printed. Expressions are evaluated and their
value is printed and assigned to the variable last. Strings
in the print statement are printed to the output and may contain
special characters. Special characters start with the backslash
character (\). The special characters recognized by bc are
“a” (alert or bell), “b” (backspace), “f” (form feed), “n” (newline),
“r” (carriage return), “q” (double quote), “t” (tab), and “\” (backslash).
Any other character following the backslash will be ignored.
{ statement_list }
This is the compound statement. It allows multiple statements to be
grouped together for execution.
if ( expression ) statement1 [else statement2]
The if statement evaluates the expression and executes statement1 or
statement2 depending on the value of the expression. If the expression
is non-zero, statement1 is executed. If statement2 is present and
the value of the expression is 0, then statement2 is executed. (The
else clause is an extension.)
while ( expression ) statement
The while statement will execute the statement while the expression
is non-zero. It evaluates the expression before each execution of
the statement. Termination of the loop is caused by a zero
expression value or the execution of a break statement.
for ( [expression1] ; [expression2] ; [expression3] ) statement
The for statement controls repeated execution of the statement.
Expression1 is evaluated before the loop. Expression2 is evaluated
before each execution of the statement. If it is non-zero, the statement
is evaluated. If it is zero, the loop is terminated. After each
execution of the statement, expression3 is evaluated before the reevaluation
of expression2. If expression1 or expression3 are missing, nothing is
evaluated at the point they would be evaluated.
If expression2 is missing, it is the same as substituting
the value 1 for expression2. (The optional expressions are an
extension. POSIX bc requires all three expressions.)
The following is equivalent code for the for statement:

expression1; while (expression2) { statement; expression3; }
break
This statement causes a forced exit of the most recent enclosing while
statement or for statement.
continue
The continue statement (an extension) causes the most recent enclosing
for statement to start the next iteration.
halt
The halt statement (an extension) is an executed statement that causes
the bc processor to quit only when it is executed. For example,
“if (0 == 1) halt” will not cause bc to terminate because the halt is
not executed.
return
Return the value 0 from a function. (See the section on functions.)
return ( expression )
Return the value of the expression from a function. (See the section on
functions.) As an extension, the parenthesis are not required.

PSEUDO STATEMENTS

These statements are not statements in the traditional sense. They are
not executed statements. Their function is performed at “compile” time.

limits
Print the local limits enforced by the local version of bc. This
is an extension.
quit
When the quit statement is read, the bc processor
is terminated, regardless of where the quit statement is found. For
example, “if (0 == 1) quit” will cause bc to terminate.
warranty
Print a longer warranty notice. This is an extension.

FUNCTIONS

Functions provide a method of defining a computation that can be executed
later. Functions in
bc

always compute a value and return it to the caller. Function definitions
are “dynamic” in the sense that a function is undefined until a definition
is encountered in the input. That definition is then used until another
definition function for the same name is encountered. The new definition
then replaces the older definition. A function is defined as follows:

define name ( parameters ) { newline auto_list statement_list }

A function call is just an expression of the form
name(parameters)“.

Parameters are numbers or arrays (an extension). In the function definition,
zero or more parameters are defined by listing their names separated by
commas. Numbers are only call by value parameters. Arrays are only
call by variable. Arrays are specified in the parameter definition by
the notation “name[]“. In the function call, actual parameters
are full expressions for number parameters. The same notation is used
for passing arrays as for defining array parameters. The named array is
passed by variable to the function. Since function definitions are dynamic,
parameter numbers and types are checked when a function is called. Any
mismatch in number or types of parameters will cause a runtime error.
A runtime error will also occur for the call to an undefined function.

The auto_list is an optional list of variables that are for
“local” use. The syntax of the auto list (if present) is “auto
name, … ;”. (The semicolon is optional.) Each name is
the name of an auto variable. Arrays may be specified by using the
same notation as used in parameters. These variables have their
values pushed onto a stack at the start of the function. The
variables are then initialized to zero and used throughout the
execution of the function. At function exit, these variables are
popped so that the original value (at the time of the function call)
of these variables are restored. The parameters are really auto
variables that are initialized to a value provided in the function
call. Auto variables are different than traditional local variables
because if function A calls function B, B may access function
A’s auto variables by just using the same name, unless function B has
called them auto variables. Due to the fact that auto variables and
parameters are pushed onto a stack, bc supports recursive functions.

The function body is a list of bc statements. Again, statements
are separated by semicolons or newlines. Return statements cause the
termination of a function and the return of a value. There are two
versions of the return statement. The first form, “return“, returns
the value 0 to the calling expression. The second form,
return ( expression )“, computes the value of the expression
and returns that value to the calling expression. There is an implied
return (0)” at the end of every function. This allows a function
to terminate and return 0 without an explicit return statement.

Functions also change the usage of the variable ibase. All
constants in the function body will be converted using the value of
ibase at the time of the function call. Changes of ibase
will be ignored during the execution of the function except for the
standard function read, which will always use the current value
of ibase for conversion of numbers.

As an extension, the format of the definition has been slightly relaxed.
The standard requires the opening brace be on the same line as the
define keyword and all other parts must be on following lines.
This version of bc will allow any number of newlines before and
after the opening brace of the function. For example, the following
definitions are legal.

define d (n) { return (2*n); } define d (n) { return (2*n); }

MATH LIBRARY

If bc is invoked with the -l option, a math library is preloaded
and the default scale is set to 20. The math functions will calculate their
results to the scale set at the time of their call.
The math library defines the following functions:

s (x)
The sine of x, x is in radians.
c (x)
The cosine of x, x is in radians.
a (x)
The arctangent of x, arctangent returns radians.
l (x)
The natural logarithm of x.
e (x)
The exponential function of raising e to the value x.
j (n,x)
The bessel function of integer order n of x.

EXAMPLES

In /bin/sh, the following will assign the value of “pi” to the shell
variable pi.


pi=$(echo “scale=10; 4*a(1)” | bc -l)

The following is the definition of the exponential function used in the
math library. This function is written in POSIX bc.

scale = 20 /* Uses the fact that e^x = (e^(x/2))^2 When x is small enough, we use the series: e^x = 1 + x + x^2/2! + x^3/3! + ... */ define e(x) { auto a, d, e, f, i, m, v, z /* Check the sign of x. */ if (x<0) { m = 1 x = -x } /* Precondition x. */ z = scale; scale = 4 + z + .44*x; while (x > 1) { f += 1; x /= 2; } /* Initialize the variables. */ v = 1+x a = x d = 1 for (i=2; 1; i++) { e = (a *= x) / (d *= i) if (e == 0) { if (f>0) while (f--) v = v*v; scale = z if (m) return (1/v); return (v/1); } v += e } }

The following is code that uses the extended features of bc to
implement a simple program for calculating checkbook balances. This
program is best kept in a file so that it can be used many times
without having to retype it at every use.

scale=2 print "\nCheck book program!\n" print " Remember, deposits are negative transactions.\n" print " Exit by a 0 transaction.\n\n" print "Initial balance? "; bal = read() bal /= 1 print "\n" while (1) { "current balance = "; bal "transaction? "; trans = read() if (trans == 0) break; bal -= trans bal /= 1 } quit

The following is the definition of the recursive factorial function.

define f (x) { if (x <= 1) return (1); return (f(x-1) * x); }

READLINE AND LIBEDIT OPTIONS

GNU bc can be compiled (via a configure option) to use the GNU
readline input editor library or the BSD libedit library.
This allows the user to do editing of lines before sending them
to bc. It also allows for a history of previous lines typed.
When this option is selected, bc has one more special variable.
This special variable, history is the number of lines of history
retained. For readline, a value of -1 means that an unlimited
number of history lines are retained. Setting the value of
history to a positive number restricts the number of history
lines to the number given. The value of 0 disables the history
feature. The default value is 100. For more information, read the
user manuals for the GNU readline, history and BSD libedit
libraries. One can not enable both readline and libedit
at the same time.

DIFFERENCES

This version of
bc

was implemented from the POSIX P1003.2/D11 draft and contains
several differences and extensions relative to the draft and
traditional implementations.
It is not implemented in the traditional way using
dc(1).

This version is a single process which parses and runs a byte code
translation of the program. There is an “undocumented” option (-c)
that causes the program to output the byte code to
the standard output instead of running it. It was mainly used for
debugging the parser and preparing the math library.

A major source of differences is
extensions, where a feature is extended to add more functionality and
additions, where new features are added.
The following is the list of differences and extensions.

LANG
This version does not conform to the POSIX standard in the processing
of the LANG environment variable and all environment variables starting
with LC_.
names
Traditional and POSIX
bc

have single letter names for functions, variables and arrays. They have
been extended to be multi-character names that start with a letter and
may contain letters, numbers and the underscore character.

Strings
Strings are not allowed to contain NUL characters. POSIX says all characters
must be included in strings.
last
POSIX bc does not have a last variable. Some implementations
of bc use the period (.) in a similar way.
comparisons
POSIX bc allows comparisons only in the if statement, the while
statement, and the second expression of the for statement. Also, only
one relational operation is allowed in each of those statements.
if statement, else clause
POSIX bc does not have an else clause.
for statement
POSIX bc requires all expressions to be present in the for statement.
&&, ||, !
POSIX bc does not have the logical operators.
read function
POSIX bc does not have a read function.
print statement
POSIX bc does not have a print statement .
continue statement
POSIX bc does not have a continue statement.
return statement
POSIX bc requires parentheses around the return expression.
array parameters
POSIX bc does not (currently) support array parameters in full.
The POSIX grammar allows for arrays in function definitions, but does
not provide a method to specify an array as an actual parameter. (This
is most likely an oversight in the grammar.) Traditional implementations
of bc have only call by value array parameters.
function format
POSIX bc requires the opening brace on the same line as the
define key word and the auto statement on the next line.
=+, =-, =*, =/, =%, =^
POSIX bc does not require these “old style” assignment operators to
be defined. This version may allow these “old style” assignments. Use
the limits statement to see if the installed version supports them. If
it does support the “old style” assignment operators, the statement
“a =- 1″ will decrement a by 1 instead of setting a to the
value -1.
spaces in numbers
Other implementations of bc allow spaces in numbers. For example,
“x=1 3″ would assign the value 13 to the variable x. The same statement
would cause a syntax error in this version of bc.
errors and execution
This implementation varies from other implementations in terms of what
code will be executed when syntax and other errors are found in the
program. If a syntax error is found in a function definition, error
recovery tries to find the beginning of a statement and continue to
parse the function. Once a syntax error is found in the function, the
function will not be callable and becomes undefined.
Syntax errors in the interactive execution code will invalidate the
current execution block. The execution block is terminated by an
end of line that appears after a complete sequence of statements.
For example,

a = 1 b = 2

has two execution blocks and

{ a = 1 b = 2 }

has one execution block. Any runtime error will terminate the execution
of the current execution block. A runtime warning will not terminate the
current execution block.

Interrupts
During an interactive session, the SIGINT signal (usually generated by
the control-C character from the terminal) will cause execution of the
current execution block to be interrupted. It will display a “runtime”
error indicating which function was interrupted. After all runtime
structures have been cleaned up, a message will be printed to notify the
user that bc is ready for more input. All previously defined functions
remain defined and the value of all non-auto variables are the value at
the point of interruption. All auto variables and function parameters
are removed during the
clean up process. During a non-interactive
session, the SIGINT signal will terminate the entire run of bc.

LIMITS

The following are the limits currently in place for this
bc

processor. Some of them may have been changed by an installation.
Use the limits statement to see the actual values.

BC_BASE_MAX
The maximum output base is currently set at 999. The maximum input base
is 16.
BC_DIM_MAX
This is currently an arbitrary limit of 65535 as distributed. Your
installation may be different.
BC_SCALE_MAX
The number of digits after the decimal point is limited to INT_MAX digits.
Also, the number of digits before the decimal point is limited to INT_MAX
digits.
BC_STRING_MAX
The limit on the number of characters in a string is INT_MAX characters.
exponent
The value of the exponent in the raise operation (^) is limited to LONG_MAX.
variable names
The current limit on the number of unique names is 32767 for each of
simple variables, arrays and functions.

ENVIRONMENT VARIABLES

The following environment variables are processed by bc:

POSIXLY_CORRECT
This is the same as the -s option.
BC_ENV_ARGS
This is another mechanism to get arguments to bc. The
format is the same as the command line arguments. These arguments
are processed first, so any files listed in the environent arguments
are processed before any command line argument files. This allows
the user to set up “standard” options and files to be processed
at every invocation of bc. The files in the environment
variables would typically contain function definitions for functions
the user wants defined every time bc is run.
BC_LINE_LENGTH
This should be an integer specifing the number of characters in an
output line for numbers. This includes the backslash and newline characters
for long numbers.

DIAGNOSTICS

If any file on the command line can not be opened, bc will report
that the file is unavailable and terminate. Also, there are compile
and run time diagnostics that should be self-explanatory.

BUGS

Error recovery is not very good yet.

Email bug reports to
bug-bc@gnu.org.

Be sure to include the word “bc” somewhere in the “Subject:” field.

AUTHOR

Philip A. Nelson

philnelson@acm.org

ACKNOWLEDGEMENTS

The author would like to thank Steve Sommars (Steve.Sommars@att.com) for
his extensive help in testing the implementation. Many great suggestions
were given. This is a much better product due to his involvement.


Index

NAME
SYNTAX
VERSION
DESCRIPTION
OPTIONS
NUMBERS
VARIABLES
COMMENTS
EXPRESSIONS
STATEMENTS
PSEUDO STATEMENTS
FUNCTIONS
MATH LIBRARY
EXAMPLES
READLINE AND LIBEDIT OPTIONS
DIFFERENCES
LIMITS
ENVIRONMENT VARIABLES
DIAGNOSTICS
BUGS
AUTHOR
ACKNOWLEDGEMENTS