home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Frozen Fish 1: Amiga
/
FrozenFish-Apr94.iso
/
bbs
/
alib
/
d8xx
/
d811
/
bsh.lha
/
bsh
/
bsh.doc
< prev
next >
Wrap
Text File
|
1993-02-14
|
87KB
|
2,301 lines
CONTENTS
(0) Features
(1) Command pre-processor (parser)
(2) Command-line editing
(3) Command-list
(4) Variables
(5) Expressions
(6) Redirection and pipes
(7) Programming
(8) Directory aliases
(9) Problems
Bsh is an enhanced shell and interpretive programming language. It
contains many advanced features not previously seen in shells on
the Amiga(TM) computer. Bsh has been tested on an Amiga 3000
running AmigaDOS1.3, AmigaDOS2.04 and AmigaDOS2.1, on an Amiga
1000 running AmigaDOS1.2 and AmigaDOS1.3, and on an Amiga 500
running AmigaDOS2.04.
MAJOR FEATURES
o Command history. Bsh remembers commands that you typed in a
history buffer; you can subsequently recall (and modify) these
commands using the command-line editing features described in
chapter 2.
o Command line editing (see chap. 2)
o Command substitution. This allows you to place the output of one
command in the command-line of another. See the IFS variable in
chapter 4.
o Redirection and piping (see chap. 6)
o Concurrent piping for external commands
o Here documents
o Command aliases
o File name completion using wildcards ('*', '?')
o Pattern permutations ({str1,str2}{str3,str4}...). Each possible
permutation becomes a separate argument for the command. For
example, to rename MyFunkyOldSourceFile.bak to
MyFunkyOldSourceFile.c:
% mv MyFunkyOldSourceFile.{bak,c}
This is not a wild-card operation, but it can be combined with
regular wildcards. For example, to remove all files ending in
.bak or .o:
% rm *.{bak,o}
o Variables, array variables and environment variables (see chap. 4)
o Expression evaluation using constants, bsh variables, arithmetic
operators and functions (see chap. 5)
o bsh scripts
o Conditionals (IF, ELSEIF, ELSE, ENDIF)
o Looping (WHILE, ENDWHILE, CONTINUE, BREAK, GOTO)
o More than 50 builtin commands (see chap. 3)
o More than 40 builtin functions (see chap. 5)
o Command search by CLI path and by bsh path variable
o Directory aliases (see chap. 8). Short abbreviations for the
current dirctory the parent of the current dirctory and the home
directory which can save lots of typing
New features in bsh 0.95
o Bsh is separated into a shared library containing most of the
code, and a very small command which just opens the library and
calls the main() entry point in it. This allows multiple shells
to be running without multiple copies of the code segment in
memory at a time.
New features in bsh 0.96
o Command hashing. When bsh finds a command in your search-path,
it remembers the location so that the next time you use the
command, it loads the command from the remembered location instead
of searching the path again. This can significantly reduce the
number of disk accesses depending on the number of directories in
your search path. The hash list can be manipulated using the HASH,
UNHASH, REHASH commands.
o Separate command newbsh creates a new shell in its own console
window.
New features in bsh 0.97
o Resident command loading. Allows pure, and pseudo-pure (linked
with LATTICE cres.o) commands to be made resident.
o Redirection of standard error file. Stderr redirection of external
(disk-based) commands requires AmigaDOS 2.0 to work.
o Bsh has been recompiled with Manx 5.0d using prototyping.
o WorkBench startup via newbsh (a tool icon is provided). Newbsh
can also be started by clicking on a script icon.
New features in bsh 0.98
o Variable exporting, bsh variables can be EXPORTed to sub-shells.
o Window manipulations with the window command.
o Bsh and newbsh have been made RESIDENTable.
o Bsh has been recompiled with Manx 5.2a.
New features to be included in bsh 1.0
o Command grouping. Commands may be grouped by placing a list of
commands within parentheses which may also contain a pipeline.
Also it is now possible to run a single command or command group
in the background or pipe the output of a group of commands into
another command.
% cmd & run command cmd in the background
% cmd1 & cmd2 run cmd1 in the background while running
cmd2
% (cmd1;cmd2) | cmd3 pipe output from group to input of cmd3
Command groups, and background commands are run in a separate
shell (bsh must be in your search path). This feature also allows
concurrent piping of script programs - they are run in a separate
shell.
The command-grouping feature is not included in version 0.98.
This will be included with bsh 1.0.
o User definable functions (really resident scripts).
o A match() function which will compare a string with a pattern and
return true if the string matches the pattern.
o Some simple form of job control (at least the ability to stop
runaway or catatonic programs and recover the use of the shell).
In the future...
Also in the planning stage, an AppWindow feature which would
allow scripts to be run by just dropping their icons into a
bsh AppWindow, and an ARexx port.
1-0 THE COMMAND LINE
Before passing a command line on to a program, bsh performs an initial
editing (parsing) pass. First any history substitution is performed.
Next, if the command line contains multiple commands or command groups,
each is extracted and treated as a separate command line. Then alias
and variable substitution is performed. Next, wildcard expansion is
performed with each matching file found occupying one argument position
on the command line. Finally, redirection files are opened, and the
redirection operators ( <, > ) and redirection file names are removed
from the command line: the program being run never sees them. Any of
the special characters recognized by the command parser can of course
be protected from their normal interpretation by quoting them.
1-1 HISTORY REPLACEMENT
See also the HISTORY command in chapter 3.
!! At the beginning of a line, causes the previous
command to be re-executed.
!string Causes the most recently entered command starting with
string to be re-executed. See the HISTORY command.
!n Causes the nth command to be re-executed.
!-n Causes the n+1th previous command to be re-executed.
Using this, you can toggle repeatedly between two
commands:
% cmd1
% cmd2
% !-1 re-executes cmd1
% !-1 re-executes cmd2
To make things even easier, you could assign the string
"!-1\r" to the variable f2, and then just keep poking
the f2 function key until done.
1-2 SEPARATORS
' ' A space; used as an argument separator. In order to
include a space within an argument, you must quote it
(see below).
; Is used as a command separator.
% cd foo ; ls
# Enter a comment. The rest of the line is ignored if it
is immediately followed by a tab or space.
% foo bar # this command does something
| The pipe operator (see below under redirection).
& Is used as a command separator. The command on the left
is run in the background; the command to the right is then
run without waiting for the first command to complete.
This requires the command grouping feature, not included in
version 0.98 of bsh. You can also run a single command in
the background by appending an & to the command.
% foo & bar Start foo in the background, then
run bar without waiting for foo.
% foo & Start foo in the background, bsh
returns to the prompt immediately.
(cmd...) Run a group of commands in a separate shell. This requires
the command grouping feature, not included in version 0.98
of bsh.
1-3 QUOTING
'string'
"string" a quoted string. For example, to set a variable to a string
containing spaces:
% set a "b c"
% echo $a
b c
% set a b c
% echo $a
b c
Within double quotes, variables are still substituted but not
within single quotes. Command substitution (`cmd`) also still
occurs within double quotes but not within single quotes.
% echo '$a'
$a
% echo "$a"
b c
\c Protects a special character from normal interpretation;
\* is an asterisk rather than all the files in the current
directory. To enter a backslash, just type "\\". This is
also used to prevent alias substitution for a command.
Within double quotes, the backslash can also be used to enter
escape characters as follows:
\a a bell - ^G (control-G)
\b a backspace (control-H)
\e an escape (control-[)
\f a form feed (control-L)
\n a newline character (control-J)
\r a carriage return (control-M)
\t a tab (control-I)
\nnn one to three octal digits representing an ascii
character of that value.
`cmd` Command substitution - execute command cmd and place its
output on the command line. Each word of output from cmd
is a separate argument for the command. Words are delimited
according to the characters in the IFS variable (see chap. 4).
If IFS is undefined, words are delimited by space, tab, or
a newline. This is a way for one command's output to become
anothers arguments. For example, add all files in the current
directory and all subdirectories to the zoo archive foo.zoo.
% zoo a foo.zoo `find . -type f -print`
You could even be a little more selective about it by piping
the output of find through pick:
% zoo a foo.zoo `find . -type f -print | pick`
If the variable IFS has been defined, it contains a list of
the characters used to delimit words. If you use 'find' to
generate a list of filenames, and the names might contain
spaces or tabs, you set IFS:
set IFS "\n"
and each line of output from 'find' is treated as one word.
Command substitution occurs within double quotes, but not
within single quotes.
1-4 REDIRECTION OPERATORS
See also chapter 6 for more information on redirection and pipes.
>file Redirect output from command. Output from the command is
directed to the named file.
>>file append output to end of the named file.
2>file Redirect standard error. Redirection of standard error
for external (disk based) commands requires AmigaDOS
version 2.0, and cooperative utilities to work.
2>>file append error file.
<file redirect standard input. The command takes input from the
named file rather than the console.
<<string here-document: lines following this line in a script file
until a line beginning with <string> are read as
standard-input by the command.
| Is the pipe operator (also a command separator). The
output from the first command becomes the input to the
second command. See chapter 6 for more info on pipes.
You can string out several commands this way, forming a
"pipeline", each command after the first takes its input
from the output of the previous command. Each command
except the last is considered a pipe-feeder.
% cmd1 | cmd2 Standard-output of cmd1 is
connected (piped) to standard-
input of cmd2.
Redirection operators are not recognized within quotes.
1-5 VARIABLE SUBSTITUTION
See also chapter 4 for more information on variables, special
variables, and special variable forms.
$name If name is the name of a bsh variable, its value is
substituted for the $name occurrence. If it is not a bsh
variable, the null string is substituted.
% set a Fred
% echo Hi, $a
Hi, Fred
${name}x Concatenates a string on to the end of a variable. This
is so bsh can tell where the variable name ends and the
string begins as in the following example.
% set a Mon
% echo ${a}day
Monday
$array[$i] Substitutes the i-th element of array if it exists.
If it does not exist, no changes are made.
% set a Bob Bill Joe
% set i 2
% echo Hi, $a[1]
Hi, Bill
% echo Hi, $a[$i]
Hi, Joe
$#array Substitutes the number of elements in an array. A zero
is substituted if the variable is not defined or is not
an array.
$?name Substitutes 1 if name is defined, else 0.
Variable substitution occurs within double quotes, but not within
single quotes.
1-6 FILENAME COMPLETION (WILDCARDS)
* Matches any string of characters of any length including
the null string.
% set a * # creates an array a, containing the
# names of all files in the current dir
? Matches any single character.
% echo ??? # echos the names of all files in the
# current dir whose names are three
# characters long.
{s1,s2} Matches either s1 or s2. These are not wildcards in them-
selves, but expand as though they had matched. If combined
with wildcards, only file names matching are expanded.
For example:
% echo {a,b,c} # even if these don't match any files.
a b c
% echo *.{c,o} # only matches existing files ending in
# in .c or .o
This can be used with the SET command to construct arrays:
% set a {0,1}{0,1,2,3,4,5,6,7,8,9} # generates an array
# of 20 elements containing 00 thru 19
Filename completion does not occur within quotes.
1-7 DIRECTORY ALIASES
See also chapter 8 for more information on directory aliases
. the current directory.
.. the parent directory of the current dir.
./f the file 'f' in the current directory.
../f the file 'f' in the parent of the current dir.
~ the home dir (specified by the home variable).
~/f the file 'f' in the home directory.
Directory aliasing does not occur within quotes.
2-0 COMMAND LINE EDITING
Command-line editing is in effect from the time bsh prints the
prompt until you press <cr> unless bsh was invoked with the -a
option. The command line can be up to 255 chars in length,
including the prompt; once the command-line has reached its
maximum length, attempts to insert a character are ignored. Bsh
will normally keep track of the line width if the window is
resized or the font size is changed.
2-1 CONTROL KEY DEFINITIONS
Control keys cause the command-line editor to take certain actions
immediately. Control keys not in the following list are ignored.
^A Toggles insert/overtype mode
^B Moves the cursor backward one word (same as shift
left-arrow)
^\ EOF - this causes bsh to quit (unless _ignoreeof
has been set)
^E Places the cursor at the end of the line
^F Moves the cursor forward one word (same as shift
right-arrow)
^H Deletes the character to the left of the cursor
^K Deletes from the cursor to the end of the line
^R Retypes the current line
^U Deletes the portion of the line to the left of
the cursor
^W Deletes from the cursor to the end of the word
^X Deletes the entire line
^Z Places the cursor at the beginning of the line
following the prompt
^- Recalls the save-buffer.
del Deletes the character under the cursor
2-2 FUNCTION KEYS
f1-f10 Function keys and their associated bsh variable names
s1-s10 Shifted Function keys and their associated variables
Help Help key
When you press a function key, if the corresponding variable is
defined, its contents are read just as though you had typed each
character of the variable. If the variable is a command, you can
then execute it just by pressing <cr>, or continue to add to the
command line. If the variable ends with a return (^M), the
command will be executed immediately without waiting for you to
press <cr>. The help key invokes the HELP command and then
reprints the command line as it was.
2-3 THE ARROW KEYS
Up arrow Recall previous commands
Down arrow Recall subsequent commands
Left arrow Move the cursor backward on the
command line
Right arrow Move the cursor forward on the
command line
Shift up arrow Partial history recall
Shift down arrow Partial history recall
Shift left arrow Move the cursor to the beginning of
the previous word
Shift right arrow Move the cursor to the beginning of
the next word
If you type a partial command string, and then a shift up arrow,
bsh will search backward for a command beginning with that string;
if one is found, it replaces the current contents of the command
line. Subsequent shift up/down arrows recall previous/subsequent
matching commands respectively. If you alter the line, it becomes
the new search string; the search string is discarded when you
execute the command.
Before searching the command history, bsh saves the current
command line in a save buffer; thus if you type an arrow key by
mistake, you can recover the line you were typing by entering a
^- (control-minus).
3-0 COMMANDS
The usual form of the command line is:
NAME [<input-file] [>output-file] [arguments]
where NAME is the command-name; for some commands (@, CD)
it is usually possible to omit the command name. The redirection
arguments can appear anywhere in the command (even before the
command-name); this is in fact the only way to redirect the output
of the EVAL command. However the pipe operator, if used must be
last, since it also serves as a command separator. The order of
search is first aliases, then builtin commands, then resident
(RES/REZ/RESIDENT) commands, followed by directories specified in
the path variable. For all builtin commands, case is significant;
they are all in lower case: Break is the DOS Break command, while
break is the builtin break command. During the command search,
scripts are treated no differently than other commands; if a script
is found in your path and it has its script bit set, it is SOURCE'd,
and any specified arguments are placed in the argv array.
3-1 BUILTIN COMMANDS
ABORT
ABORT [exit-code [error-number]]
Causes the remainder of the command line to be discarded. Used
with exception processing (see chapter 7). ABORT will also set
the exit-code and error-number if these are passed; this can be
used to restore the values which are normally cleared after each
command.
% echo a;abort;echo b
a
ALIAS
ALIAS
ALIAS name
ALIAS name command...
Declares name to be an alias for the command(s) specified. In
order to specify more than one command, you must use quotes
around the entire list of commands.
% alias frog "echo hop hop; echo hop; echo hop hop hop"
then you can just type 'frog'. All arguments to the alias are
placed in the variable '!' which you can reference anywhere in
the alias string:
% alias rdonly protect $! -wd
% alias inc @ $!++
% rdonly *.c
% i=0
% inc i
% echo i = $i
i = 1
Additionally, you can use aliases to change the default options
for commands:
% alias rm rm -i
% alias ls ls -l
Henceforth every time you use the rm command, it will prompt for
each file before deleting it; ls will now give the long listing
by default. Bsh detects the recurrence of the command and
prevents the alias from becoming recursive.
If an alias has the same name as a normal command, you can still
use the normal command by preceding the command with a backslash.
% \rm *.info # remove .info files without prompting
% \ls # print the short file listing
See also UNALIAS
ARRAY
ARRAY varname[size] ...
ARRAY varname ...
Declares varname to be an array of size elements. If varname
already exists, its contents are lost. When the array is created,
is is filled with NULL strings; these values are not considered
to be numeric. You must assign values to the individual elements
before using them in expressions. The second form can be used to
convert a simple variable into an array of one element; array
variables remain unchanged. Arrays are singly dimensioned and are
limited to no more than 32767 elements.
BREAK
BREAK
Break out of a while loop; execution continues with the next
command following the corresponding endwhile for the current
level of loop. The BREAK command is used to prematurely exit a
loop. BREAK is restricted to script files.
CAT
CAT
CAT [file....]
Copies the specified files to stdout (the current window, unless
output has been redirected). If you don't specify a file, stdin
is copied. You can cat standard input along with other files by
specifying - (minus sign) alone as a file name. You can also use
CAT to join binary files together by redirecting the output to a
file.
% cat a types a to the current window
% cat - bar >foo copies stdin + bar to foo
% cat a b c >prt: copies a b and c to the printer
CD
CD
CD path
Changes the current working directory. You may use any of the
directory aliases here (see Directory Aliases in chap. 8).
CD with no arguments changes the current directory to the
directory specified in the home variable, or if the home variable
is undefined, CD just displays the path of the current directory.
If you enter a directory name by itself on a line, then bsh
implicitly changes the working directory to that dir. This is
only done if the path search fails to find a command of the same
name and the dir name does not conflict with an internal command.
CLOSE
CLOSE fd...
Close a file. fd is the file descriptor returned by the open()
function. The FILES command will list the file-names and
descriptor numbers of all open files. You cannot use CLOSE to
close files opened by some other program. Care should be used
with this command, as it is possible to close files which are
still in use such as script files and redirection files.
CONTINUE
CONTINUE
Advance to the next iteration of a while loop; execution
continues with the while command at the top of the loop.
CONTINUE is restricted to script files.
CP
CP file... dev
CP [-AacdeNnu] file file
CP [-AacdeNnu] file... dir
CP [-AacdeNnru] dir... dir
-A Set archive bit on source files after successful copy.
-a Set archive bit on destination files.
-c Causes cp to copy the file-protection bits and comment
from the original file to the destination file.
Otherwise the protection mask is set to ----rwed.
-d date - set file timestamp to current time and date.
Default is to retain the original timestamp.
-e Copy only files which already exist in destination
directory.
-N Copy only files which have been modified (archive bit
is not set).
-n Copy only files which do not exist in destination
directory.
-r Recursively copy all subdirectories.
-u Update - copy file only if destination file is older
or does not exist.
Copies files and directories. To recursively copy all
subdirectories of the directories specified on the command line,
the "-r" option must be used. If "-r" is not specified, each
file in dir is copied, but none of the sub-directories in dir is
copied. When copying recursively, directories will be created
automatically, if they do not already exist.
Using the first form, it is possible to copy several files to a
DOS non-filing-system device (E.G. PRT:); in this case, there
are no applicable options.
examples:
% cp this that PRT: # copy files to the printer
% cp -u ~ . # copy files from the home directory to
# the current dir; only copy file if it
# is newer.
% cp *.c prt: # copy all .c files in the current dir
# to the printer.
CP has no quiet option but can be made to copy quietly by
redirecting stderr:
% cp dir1 dir2 2>NIL:
ECHO
ECHO [-n] string...
Write the strings to standard output (the current window unless
output has been redirected). A newline character is appended to
the end of string unless '-n' is specified.
ELSE
ELSE
ELSE clause of a block if; this toggles the value of the matching
IF condition. Only one ELSE is allowed for each IF command.
ELSEIF
ELSEIF expression
ELSEIF clause of a block if; if the matching IF condition was
true, it is now false; if it was false, it is now true if
expression evaluates to true (non-zero). Any number of ELSEIFs
may be associated with one IF.
example:
if a < 10
...
elseif a < 20
...
else
...
endif
ENDIF, FI
ENDIF
FI
The end of the scope of a block IF statement.
ENDWHILE
ENDWHILE
The of the scope of a while loop.
See also WHILE
@, EVAL
@ expression
EVAL expression
@ and EVAL both evaluate an expression (see expressions below)
After evaluating the expression, EVAL prints the value to the
standard output, whereas @ does not. If the _debug variable is
set to 8, expression values are always printed to standard error
when evaluated. If you enter an assignment expression on a line
by itself, bsh will execute an implied @ command using that
expression. If you wish to redirect the output of EVAL, you
must place the redirection operator before the command name:
% >foo eval 1+1
it is not currently possible to pipe the output of eval to another
command.
examples:
% eval sqrt(4)
2.0000000
% @ j=5
% x=sin(.543)
% echo $x
0.51670675
See also expressions in chapter 5.
EXPORT
EXPORT varname...
Sets the export flag for varname; variables which have the
export flag set are exported to sub-shells of the current shell
(they inherit its value). This includes all shells started by
bsh or newbsh commands from the current shell. Script local
variables cannot be exported.
FILES
FILES
Lists all files currently opened by bsh. This includes files
opened by the open() function, files opened by redirection
( >file ), and script files currently being executed.
Information includes the file name, the file descriptor number,
and whether the file was opened for read or write access.
FOREACH
FOREACH var ( list ) command...
FOREACH var ( list )
command
...
END
For each argument in list, the argument is assigned to the
variable var, and then each of the commands is executed in turn.
If more than one command is given with the first form, they must
be enclosed in quotes. Foreach does not require a space between
the open parenthesis and the first argument; however if the first
argument contains a wildcard, then you must include the space for
wildcard expansion to work properly; the same is true between the
last argument and the closing parenthesis. Only the first form
of FOREACH can be used in an alias definition.
% foreach i (1 2 3) echo "$i is a digit"
1 is a digit
2 is a digit
3 is a digit
% foreach i ( *.o ) # remove .o files
> j=basename(i)
> if -f $j.asm # for which the source is in assembly
> rm -q $i
> endif
> end
FOREACH can be used to interpret arguments of a parameterized
alias:
% alias xx "foreach i ( $! ) echo \$i"
% xx * echos the names of all files in the
current directory
You may not use a GOTO or WHILE command inside a FOREACH; however
you can have calls to source scripts which do include GOTO and
WHILE commands. Also it is not possible to nest FOREACH commands.
GOTO
GOTO label
GOTO the named label. Command execution continues with the
command immediately following the label. GOTO is restricted
to script files.
HASH
HASH
HASH command
HASH command path
Display the hash tree, display the hash-path for a command, add
a command and path to the hash tree. Bsh searches the hash tree
when the hash-operator (#) is included in the path variable.
The use of this reduces the search time and disk accesses
required to locate an external (disk-based) command. No action
by you is required to take advantage of this feature, as bsh
automatically adds names of commands to this tree when it finds
them while searching your path. The HASH command allows you to
manipulate this tree. The filename part of path need not match
command.
Examples:
% hash ls work:bin/ls # add ls to the hash tree
% hash # display the hash tree
ls work:bin/ls
vi work:bin/z
See also UNHASH, REHASH
HELP
HELP
Displays all the bsh builtin commands and predefined functions.
The commands are displayed columnwise in alphabetical-order.
HIST
HIST [string]
Displays the history list with event numbers (The number of
events remembered in the history list is determined by the
bsh _history variable). If a string is specified, only those
entries starting with string are shown.
IF
IF expression
IF test expr
Execute following commands (through ELSE/ELSEIF/ENDIF) if
expression evaluates to true (non-zero). The IF command is not
restricted to source files, and may be used interactively. You
can see whether the expression is true by using it with the
EVAL command. The structure of an IF block is something like
this:
if expression
commands
...
elseif expression
commands
...
elseif expression
commands
...
else
commands
...
endif
The ELSEIF/ELSE clauses are of course optional. If blocks may be
nested up to a maximum depth of 32. The nesting depth is reset at
zero for each script file, so you could be nested at say level 23
in one script file called from another at a depth of 31.
The second form of IF involving the test command is included
mainly for compatiblity with Bourne shell scripts. See the
separate documentation for test for format of test expressions.
Bsh's own expression evaluation is much more powerful and easier
to use than that of the test command.
examples:
if a < 10 if variable a is less than 10
somecommand
endif
if -z fred if file fred exists and is empty
mv fred ..
endif
if ?x if variable x has been defined
if a[5] != 0 if element 5 of a is non-zero
x /= a[5]
else
echo a[5] is zero
endif
eval x
endif
See also expressions in chapter 5.
LABEL
LABEL name
Define a label name; used as the object of a GOTO. Labels can
only be used within a script file. When LABEL is used, it
should be the first command on a line as GOTO can only branch
to line boundries.
LOCAL
LOCAL varname[=value]...
LOCAL arrayname[#elements]...
LOCAL must be used from within a bsh script file; it creates a
variable local to that script. If a global or environment
variable of the same name exists, it is masked (becomes
invisible) within the script. In order for a variable to become
local to a script, it must be declared local (with the LOCAL
command) before any other reference to it. When a script exits,
all variables local to that script are automatically destroyed.
You cannot initialize an array with the LOCAL command.
% local i j=1 ar[20] k=2 l
% set ar {0,0,0,0,0}{0,0,0,0} # initializes ar with zeros
MEM
MEM
Display memory availability for CHIP and FAST memory. The
advantage of using MEM over Avail is that MEM is an internal
command and thus does not disturb the memory availability in
order to print it.
MKDIR
MKDIR name name name...
Create directories. If name already exists, MKDIR returns
exit-status 5 (WARN) if name was a directory, or exit-status
10 (ERROR) if name was a plain file.
MV
MV from to
MV from... todir
Rename a file or move one or more files or directories to a
different directory. If todir is "/" or "..", the files are
moved to the parent directory; if todir is ".", the files are
moved into the current directory. Currently MV cannot move
files across devices (MV df0:a df1:). MV will complain if you
try to move a directory inside itself or inside one of its
subdirectories. MV returns an exit-status of 10 (ERROR) if the
destination file already exists or todir does not exist or your
try to mv a dir inside itself.
ONERR, ONINTR
ONERR command...
ONINTR command...
ONINTR specifies the command(s) to be executed when an interrupt
(^C,^D) is encountered when executing a script. If ONINTR has
been specified, the interrupt signals are reset before executing
the command(s). ONERR specifies the commands to be executed when
an error occurs while executing a script. See also the onerr,
and onintr variables. You can also set a global ONERR, which
specifies commands to be executed if an error occurs while
executing commands entered interactively, from the command line.
If multiple commands are given, they must be enclosed in quotes.
PICK
PICK [item...]
PICK prompts you for every item specified on the command line, and
for each item you respond positively, writes its name to standard
out. If no items are specified, PICK reads its standard input for
items, one item per line. For each item in the list, PICK prompts
with:
item [ynaveq] ?
available responses are:
y yes, choose this item
n no, do not choose this item
a select this item, and all remaining items in the list
v view this item; uses program specified in the environment
variable PAGER to view the item. If the variable PAGER
does not exist, the program More is used. This only makes
sense if item is a file.
e edit this item; uses program specified in the environment
variable EDITOR to edit the item. If the variable EDITOR
does not exist, the program Ed is used. This only makes
sense if item is a file.
q quit
!cmd run cmd. A '%' character in the command is replaced by
the current item.
PICK is best used to restrict command line arguments generated by
wildcard search or by some other program:
% cp `pick *.c` df1:foo select which *.c files to copy
% mv `find . -print | pick` a select which files to move from
list generated by 'find' to dir a.
% pick * | zoo aI foo.zoo select which files to archive
PRINTENV
PRINTENV
Displays the values of the environment variables. PRINTENV only
displays those files in the ENV: directory (not in subdirectories).
PWD
PWD
PWD file...
Print the current directory name if no files given. If files are
specified, the absolute DOS path to each is printed.
QUIT
QUIT [value]
Quit bsh. If you specify a value, bsh exits with the optional
exit-code. (see RETURN below)
READ
READ varname...
Read variable(s) from stdin. One line is read and split according
to IFS (see special variables). Data are matched with the
specified variable names. Any excess data is discarded; if there
is less data than variables, the remaining variables are set to
the null string (""). You cannot read an entire array just by
specifying the array name; you must list the individual elements
to be read.
% read a b c[2] c[3]
REHASH
REHASH
Delete the entire hash tree. See the discussion under HASH above.
REPEAT
REPEAT count command
Repeatedly execute a command. The count can be an expression but
if it contains any of '|; ><' you will have to enclose it in
quotes. Command may be several commands separated by semi-colons.
If it is, the entire list of commands should be enclosed in quotes.
You may not use a GOTO, WHILE or FOREACH command inside a REPEAT.
EXIT, RETURN
EXIT [expression]
RETURN [expression]
Return from a script file. If given, the expression value becomes
the return value for the SOURCE command. In a function script,
this value is RETURN'ed as the function value. In a startup
script, EXIT functions as a QUIT command, that is bsh is prevented
from going into interactive mode; once bsh has gone into interactive
mode, EXIT functions only as a return. This allows you to set up
scripts which will run normally if entered from the command line,
but quit after running the script when entered:
% bsh <scriptfilename>
REWIND
REWIND fd...
Rewind a file; the file is positioned at its beginning. Fd is a
file descriptor returned by the open() function.
RM
RM [-iqr] file...
Delete the specified files or empty directories. Use the "-r"
option to remove non-empty directories by recursively removing
all sub directories and files they contain. The -i option will
cause bsh to prompt for each file with:
filename [ynaveq] ?
before it is deleted; see the PICK command for responses. RM
returns errorcode 5 (WARN) if the file did not exist or 10
(ERROR) if RM could not delete the file because it was busy.
The -q option causes RM to do its work quietly, otherwise each
file is listed as it is deleted.
SET
SET
SET name
SET name string...
The first form displays all bsh variables and their values. The
second form displays the value for a single variable. The last
form sets a variable to a string or array of strings. To include
a space in the value for a variable, you must quote the value.
See also UNSET
see the section on special variables below
SETENV
SETENV name string
Set an environment variable. The environment variables are really
files in the ENV: directory. This probably should be assigned to
some directory on your ram: disk by your startup-sequence.
Environment variables are referenced in the same way as other bsh
variables with the exception that environment variable names are
not case sensitive. If an environment variable and a bsh variable
have the same name, the bsh variable overrides. Also environment
variables cannot be arrays at this time.
% setenv NAME Fred
% echo $name
Fred
SLEEP
SLEEP [time]
Sleep for <time> seconds. If <time> is not specified, bsh takes
a one second nap. Time may be specified with or without a
fractional part (n.nn). The resolution of <time> is .02 seconds.
SOURCE
SOURCE script-file [arguments]
Execute a script file. Normally, you just type file [arguments];
the main advantage to specifying SOURCE explicitly is that it
does not require that the script and execute permission bits be
set for the file. Note that when you specify SOURCE explicitly,
the path is not searched for file; you must specify the path for
the file unless it is in the current directory. Arguments are
passed via the argv[] variable. The name of the source script
is in argv[0], the ith argument to the script is in argv[i].
See also argv under special variables in chap. 4. Some commands
such as GOTO and WHILE can only be used in script files.
Scripts are useful to replace a frequently used or long sequence
of commands with a single, easy to remember command. They are
also useful in dealing with some program's clumsy user interface.
Also, scripts can often be used in place of a C program, and are
much easier to write and debug. For more info on script
programming, see chapter 7.
THEN
THEN
THEN does absolutely nothing whatsoever. It is included only for
compatibility with Bourne-shell scripts.
UNALIAS
UNALIAS name...
Removes bsh aliases from the alias tree.
See also ALIAS
UNHASH
UNHASH command
Removes a command name from the hash tree.
See also HASH, REHASH
UNSET
UNSET name....
Removes bsh variables from the variable tree and frees all space
used by each for strings, arrays.
See also SET
UNSETENV
UNSETENV name....
Removes the named environment variables. This deletes the
ENV:name file.
See also SETENV
VER
VER
Displays the version number of bsh, along with its date.
WHILE
WHILE expression
Repeat statements while expression is true (non-zero). WHILE can
only be used in script files. While loops may be nested up to a
maximum depth of 10.
example:
while a < 10
a++
...
endwhile
See also expressions in chapter 5.
See also ENDWHILE
WINDOW
WINDOW [parent | child]
WINDOW [back | front | activate | zip]
WINDOW x y width height
WINDOW
Manipulate the bsh window. Using this command, you can move
the bsh window in back of all other windows, in front of all
other windows, activate the window, change its dimensions,
toggle between two sizes (zip, requires DOS 2.0), or activate
the child or parent of the shell's window. Be careful - you
can set the window width and height to zero if it has no size
gadget; the window will then be very hard to find. Also, any
changes to the window size made while the window is not the
active window are apparently missed by the console (I think
this is fixed in DOS2.0) With no arguments, WINDOW prints the
current window coordinates and bounds; you can use this to save
the current window bounds and restore them later:
% set wndw `window` # save current window bounds
% window 0 0 640 400 # change window size...
...
% window $wndw # restore window to previous
# bounds
The zip function requires AmigaDOS2.04 to operate.
Keyword arguments may be abbreviated to a single letter.
3-2 OTHER COMMANDS
BSH
BSH [-a] [startup-script]...
BSH -c command;command...
Startup a bsh shell in the current CLI window. The -a switch
is useful when you want to suppress bsh's command-line editing
features. It is possible to use the command-line editing features
in an AUX: CLI. The second form can be used to gain bsh services
in running a command (i.e. wildcards, pipe, etc.). At startup,
bsh first reads and executes the file .bshrc in the current
directory if it exists, or s:.bshrc. Next if the -c switch was
selected, command is executed and bsh then quits, else any startup
scripts specified on the command line are executed. Then bsh
executes the file .login in the current directory if it exists,
or s:.login and then enters interactive mode. If a QUIT or EXIT
command was encountered during execution of a startup script, bsh
will quit without entering interactive mode.
NEWBSH
NEWBSH [window-spec] [-a] [[FROM] startup-script...]
NEWBSH [window-spec] -c command...
Startup a new bsh shell in a different window. The FROM keyword
is only required if the first argument would be a startup script,
to distinguish it from a window specification. NEWBSH can be
started from WorkBench by double-clicking on the NEWBSH tool
icon, or by double clicking on a script icon. Some sample icons
are provided. You can also extended select several script icons,
and NEWBSH will execute each of them in turn. If any of the
scripts contain a QUIT or EXIT command, NEWBSH will quit after
executing all of the scripts; otherwise NEWBSH will enter
interactive mode, accepting command input.
4-0 VARIABLES
Bsh like other shells uses only string variables. However, some
commands that work with expressions, can perform arithmetic on
these variables as numbers. These special commands are @, EVAL,
IF, ELSEIF, RETURN, and WHILE. In this context, a numeric variable
is really a string variable that contains only digits with a leading
sign or hexadecimal radix (0x), a decimal point and an exponent.
Internally, variables are stored in a binary tree for fast access.
A variable name consists of any number of characters chosen from
letters, digits and the underscore.
Variables may be set (assigned a value) by the SET command, or by
use of an assignment operator in an expression.
4-1 VARIABLE SUBSTITUTION
When a variable has been assigned a value, bsh replaces occurences
of that variable on command lines with the assigned value. Bsh
recognizes a word as a variable if it begins with a dollar sign.
You can protect a word from variable substitution by preceding the
dollar sign with a backslash (\$). Variable substitution occurs
even if the variable name occurs within a string enclosed in double
quotes, but not in a string enclosed in single quotes. Environment
variables are referenced in the same manner as regular bsh
variables on the command line; however they cannot be assigned a
value in an expression. Within an expression, variables are
referenced without the leading dollar sign.
4-2 ARRAY VARIABLES
Before you can manipulate the elements of an array, the entire array
must be declared. Arrays can only be declared using the SET, or
ARRAY commands:
% set days Sunday Monday Tuesday Wednesday Thursday Friday Saturday
% echo $days
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Individual array elements may be referenced by postfixing the array
name with an element number enclosed in square brackets; the
element number can also be a numeric variable. A range of elements
can be referenced by the first element number followed by a dash
followed by the last element number. An asterisk can be used to
indicate all elements of the array, an asterisk can be used after
the dash to indicate the last element of the array.
% echo $days[3]
Wednesday
% echo $days[1-5]
Monday Tuesday Wednesday Thursday Friday
% set i 2
% echo $days[$i]
Tuesday
% echo $days[$i-*]
Tuesday Wednesday Thursday Friday Saturday
All elements must be assigned a value when the array is declared
(a NULL or 0 may be used if the desired value will not be known
until later). The SET command counts the number of items on the
command line and allocates enough memory for that many elements.
The ARRAY command allocates enough storage for the specified
number of elements, and fills them all with NULLs.
4-3 SPECIAL VARIABLE FORMS
The number of elements of an array can be referenced by using the
form:
$#array_name
The existence of a variable can be queried by the form:
$?var_name
This form returns 1 if var_name has been defined, and 0 if it has
not been defined. You can also use this to determine whether an
array has a specified number of elements:
$?array[5]
returns a 1 if array has at least 6 elements.
You can catenate a plain string to the end of a variable on the
command line if you enclose the variable name in braces:
% set dow Sun
% echo ${dow}day
Sunday
4-4 SPECIAL VARIABLES
Variable names starting with an underscore ('_') have a one to one
connection with flags/counters deep in the heart of bsh. For this
reason, their intended effect cannot be accomplished using environ-
ment, or local environment variables.
argv
*
This array variable contains the arguments passed to a script
program. Each argument is an element of the array. For
example:
script-file printargs
local i
echo $argv
echo $*
set i 0
while i < #argv
echo argv[$i] = $argv[$i]
i++
endwhile
% printargs 1 2 4
printargs 1 2 4
1 2 4
argv[0] = printargs
argv[1] = 1
argv[2] = 2
argv[3] = 4
Individual arguments may be addressed as $argv[4], $argv[$i]...
argv[0] contains the script file name; the remaining arguments
may be referenced as a group by $*. $* is equivalent to
$argv[1-*]. Any of the first 10 elements may be referenced by
short form; $1 is equivalent to $argv[1]...
commands
Contains the count of commands executed since bsh was started.
This is maintained by bsh, however, it is not always updated
after every command; if you exececute a script file, it will
not be updated until the script completes. This variable is
read-only.
cwd
Contains the absolute path of the current working directory.
This variable is maintained by bsh each time you change the
working directory with a CD command or an external (disk-based)
command changes the current directory. This variable is read-only.
_debug
Debug modes. The following debug modes are supported:
0 no debugging
1 print command arguments prior to executing
each command
2 print redirection file names (console is
indicated by an asterisk).
4 print depth of variable names in variable
tree (applies to set, hash, local and alias
commands only).
8 print expression values when they are evaluated
(by @, EVAL, IF, ELSEIF, RETURN, WHILE)
16 print exit status, and DOS error number after
each command executed.
32 print actual command line (after all variable
substitutions, and wild-card expansion). As an
alternative to _verbose, this prints only those
commands that are actually executed. If used
with mode 2, both outputs are combined on 1 line.
Set _debug to the sum of the desired debugging modes. Debugging
output is written to the stderr file. _debug must be a bsh
variable (not an environment variable for this to have any effect).
errno
This variable contains the DOS error number from the last command.
To obtain an English translation, feed it to Fault:
% Fault $errno
Remember that this variable is reset after each command, so you
will have to assign it to some other variable first if you plan
to manipulate it. For the custom bsh error numbers, you can use
the error script provided:
% error 909
error 909: reference to undefined variable
height
Maintained by bsh, this is the height of the console window in
lines. If you resize the window, bsh will update this variable
to reflect the change.
histnum
This variable contains the event number of the next command to be
executed. This value is substituted for '!' in the prompt or
title. This variable is read-only.
_history
This variable specifies the number of history events bsh should
retain. Consecutive identical history items are entered in the
history list only once. _history must be a bsh variable (not an
environment variable for this to have any effect).
home
This is the home directory variable; it contains the full path
specification for the home directory. It is substituted for a
leading ~ in file name/path specifications. This variable is
automatically set by bsh at startup, but you can alter it at any
time.
examples:
% cp ~/foo . copies the file foo from the home directory
to the current directory.
% ls ~ lists the files in the home directory.
IFS
Contains the characters that serve as argument separators when
command output is being substituted on the command line or when
variables are being read (READ command). If IFS is not set,
the value " \n\t" (space, new-line, tab) is used.
_ignoreeof
If defined, EOF is ignored on consoles. Use this to prevent
accidentally exiting bsh. You can still exit bsh by entering
the QUIT command. _ignoreeof must be a bsh variable (not an
environment variable for this to have any effect).
insert
This variable controls the default screen insert/overlay mode.
If insert is set to 0 (zero), the default mode is overlay, else
mode defaults to insert. If insert is not set, insert is the
default mode. Of course you can always toggle between modes
by typing a ^A during command entry.
_noclobber
If set to some value, output redirection will fail if the file
already exists; append redirection will fail unless the file
already exists. Use of this variable can sometimes keep you
from accidently clobbering an important file. _noclobber must
be a bsh variable (not an environment variable for this to have
any effect).
_noglob
If set to some value, inhibits wildcard expansion. Use this if
you want an external program to do it's own wildcard expansion,
or when symbols normally used as wildcards have a different
meaning. _noglob must be a bsh variable (not an environment
variable for this to have any effect).
_nonomatch
If set to some value, will not complain when a wildcard string
fails to find a match; instead, if the match fails, the string
will be passed on to the command to be executed. _nonomatch
must be a bsh variable (not an environment variable for this to
have any effect).
_noreq
If set to some value, will disable requesters ("Please insert
volume fred in any drive") during the path search for external
commands. _noreq must be a bsh variable (not an environment
variable for this to have any effect).
path
This contains the search paths used to find external commands.
path is an array variable containing a list of directory-names
to be searched, and optionally some special elements:
'!' Search the CLI path. This does not include the
current directory, or C:. See the example set path
below for how to include them.
'#' Look for the command in the hash list.
'0' Turn off requesters for following directories. If
path contains, say, fred:c, and volume fred: is not
mounted, you can avoid a requester saying "Please
insert volume fred in any drive".
'1' Turn requesters back on.
The path variable is not used if the command is in the system
RESIDENT list, or the command name contains pathing information
(contains a ':' or '/'). The suggested set value for path is
% set path '.' '#' '!' sys:scripts c:
This assumes that your bsh scripts are in the sys:scripts directory.
There is no default value for path.
pipe
This variable contains the name of the pipe device which will be
used when piping output from one command to input of another. If
pipe is undefined, temporary ram: files are used instead. If set
to "PIP:", it is assumed to be a conman PIP: pipe device; case is
significant.
prompt
This string is displayed when bsh is expecting interactive input
from the user. Special characters recognized are:
! the value of the variable histnum (event number)
` the current time (HH:MM)
`` the current time (HH:MM:SS)
\ used to protect the following character from
interpretation; to get a \, use \\.
$name the value of the variable name (any bsh variable)
If this should be evaluated each time the prompt
is printed, the name should be escaped as in
\$name; this will prevent the command parser from
evaluating the variable immediately.
If commands are being skipped because you executed an IF command,
bsh changes the prompt to "? ". You must then enter an endif
command before command execution resumes.
PS2
This is the secondary prompt used when bsh is expecting interactive
input from the foreach command:
% set PS2 "huh? "
% foreach i ( a b )
huh? echo $i
huh? end
a
b
If PS2 is not defined, the value "> " is used.
status
Exit-status of the last command. This is set after each command
executed, so it is necessary to query this immediately or its
value will have changed.
_title
This string is printed in the window title line. Special
character processing is the same as for the prompt string. _title
must be a bsh variable (not an environment variable for this to
have any effect).
_umask
This variable controls the permission bits set for files opened
by bsh for output redirection. The variable must be set to the
sum of the desired permission bit values (use 15 for rwed, 13
for rw-d, etc). The permissions for the file are set after the
file is closed. _umask must be a bsh variable (not an environment
variable for this to have any effect).
_verbose
Enter verbose mode (for scripts). This mode displays commands as
they are read from the script file. Debugging output is written
to the stderr file. _verbose must be a bsh variable (not an
environment variable for this to have any effect).
width
Maintained by bsh, this is the console width in chars. If you
resize the window, bsh will update this variable to reflect the
change.
5-0 EXPRESSIONS
The commands - @, ELSEIF, EVAL, IF, RETURN, and WHILE evaluate and
utilize C-like expressions in the perfomance of their functions.
Expressions consist of strings, numeric constants, bsh variables,
function references and operators. You can freely insert spaces
anywhere in an expression except in compound operators variable
names or numeric strings. Within expressions variable names may
be used without the leading dollar sign ($). If you use a leading
dollar sign, the variable is replaced by the command parser and
looks like a constant to the expression evaluator. Numerical
operations are performed on 32-bit signed ints or 32-bit FFP
floating point operands. Variables have no intrinsic type, but
assume the type of the data they contain. The arithmetic and
relational operators will all allow mixed mode operands. That is
an int can be added to a floating point operand or compared to
a floating point operand; in this case, the int is first converted
to floating point and then the operation is performed. Environment
variables may also be used within expressions, but may not be
altered by an assignment operator within an expression; use the
setenv command to alter environment variables.
5-1 OPERATORS
The following is a list of bsh operators in order of precedence
from highest to lowest.
() override precedence of operators
?var test the existence of a variable (this is similar to the
$?var special form [see chap. 4-3]).
#array number of elements in an array (this is similar to the
$#array special form [see chap. 4-3]).
~ unary one's complement
! logical not
- unary minus
++ increment a bsh variable (var++, ++var)
-- decrement a bsh variable (var--, --var)
% modulus
/ division
* multiplication
- subtraction
+ addition
<< left shift
>> right shift
> greater
< less
>= greater or equal
<= less or equal
!= not equal
== equal
& logical product
| logical sum
^ exclusive or
&& logical and
|| logical or
= assign a value to a bsh variable
+= increment the value of a bsh variable
-= decrement the value of a bsh variable
*= multiply the value of a bsh variable
/= divide the value of a bsh variable
%= assign the modulus value of a bsh variable
, comma operator (comma is a binary operator which
returns the value of the subexpression to the right
of the comma). That is, a = (b,c) assigns the value
of c to a. The comma is also used to separate
function parameters, and to separate multiple
assignments in an expression:
% a=1,b=2,c=3
IMPORTANT: The decrement and increment operators are pre-increment
(++var) and post-increment (var++). In either case, the variable
is incremented, but the value used in the expression is that of
the variable before incrementing (post-increment) or after
incrementing (pre-increment). That is, if i has the value of 1,
then j = i++ assigns the value of 1 to j while incrementing i to 2.
These operators can only be used with integers.
In addition, file operators operate on following filename.
Boolean operators:
-A file has been archived
-D file has delete access
-d file is a directory file
-e file exists
-f file is a plain file
-o file exists
-P file is pure
-r file has read access
-S file is a script file
-w file is writeable
-x file is executable
-z file is empty
Operators which return a value:
-m time of last modification (seconds since 1/1/1978)
-p file protection string (hsparwed)
-s size of file in bytes
-T date file was last modified
-t time file was last modified
Examples:
% eval str=-T fred
26-Nov-89
% eval str=-p fred
----rwed
% if -f fred
% echo fred is a plain file
% endif
A variable containing a file name must be prefixed by a dollar sign ($)
when it is the object of a file operator.
% if -s $file > 1000
% echo $file is larger than 1000 bytes
% endif
5-2 FUNCTIONS
The following functions are predefined by bsh:
abs(num)
returns the absolute value of num.
acos(num)
returns the angle whose cosine is num.
asin(num)
returns the angle whose sine is num.
atan(num)
returns the angle whose tangent is num.
basename(str)
returns the base filename of str. If str is "foo.c",
basename(str) returns "foo".
cat(str1,str2,...)
concatenates strings.
char(num)
returns the character whose ascii value is num. This provides a
means to convert small integers to characters.
cos(num)
returns the cosine of num.
cosh(num)
returns the hyperbolic cosine of num.
date()
returns the current date in MM/DD/YY format.
devname(str)
returns the device name portion of string. If str is
"df1:foo", devname(str) returns "df1".
eof(fd)
returns true if EOF was read on file fd (fd is a file
descriptor number as returned by open()). Calling the eof()
function has the side-effect of clearing the EOF condition for
the file.
exp(num)
returns the exponential of num (e**num).
filename(str)
returns the file-name stripped of path.
float(num)
converts an integer to floating point.
getchar()
reads a character from stdin and returns it.
hex(num)
converts num to a hexadecimal string.
index(str,"c")
returns the position of first occurence of "c" in str. Returns
-1 if "c" not found in str.
% eval index("abc","c")
2
% eval index("abc",99) 99 is the ascii value of 'c'
2
int(num)
converts num to integer.
left(str,num)
returns the leftmost num characters in str.
log(num)
returns the natural logarithm of num.
log10(num)
returns the base 10 logarithm of num.
lower(str)
returns str transformed to lower case.
max(num1,num2)
returns the maximum of two numbers.
min(num1,num2)
returns the minimum of two numbers.
mounted(device)
returns true if device has been mounted and bsh is able to
obtain a lock on it; this only works for filing-system devices.
numeric(str)
returns true if str is a numeric string.
open(filename,mode)
opens a file, and returns the file descriptor number. Available
modes are:
"a" - append
"r" - read
"w" - write
pathname(str)
returns the path name portion of string.
pow(base,exp)
returns base raised to the exp power. This is a floating point
function, but will return an integer if both arguments are
integer.
ran(max)
generates a random integer in the range (0 <= num < max). Max
must be < 4194304 (2**22).
right(str,num)
returns the rightmost num characters in str.
rindex(str,"c")
returns the position of last occurence of "c" in str. Returns
-1 if "c" not found in str. See also index.
rtime()
returns the number of ticks since midnight. There are 50 ticks
per second.
sin(num)
returns the sine of num.
sinh(num)
returns the hyperbolic sine of num.
size(var)
returns the size of array (1 indicates scalar, 0 undefined)
sqrt(num)
returns the square root of num.
strlen(str)
returns the length of str.
substr(str,first,len)
extracts a substring from a string starting with character
numbered first, of length len.
% eval substr("abcdefg",3,3)
cde
tan(num)
returns the tangent of num.
tanh(num)
returns the hyperbolic tangent of num.
time()
returns the current time in HH:MM:SS format.
upper(str)
returns str transformed to upper case.
Additionally, any bsh script file may be used as a function; it
returns a value via the RETURN command. As with any other bsh script,
arguments are passed to the function in the argv variable:
funcname([arg]...) user defined function
File funcname must be somewhere in your path.
6-0 REDIRECTION AND PIPES
You can now specify the type of PIPE you wish to use in the bsh
variable pipe. If this variable is undefined, PIPES are
implimented as temporary ram: files. These files are
automatically deleted upon completion of the pipe segment. To use
the new 1.3 Pipe.device, you need only set the pipe variable:
% set pipe PIPE:
To use the Conman pip: device as a pipe:
% set pipe PIP:
Case is significant. You should probably place one of the above
commands in your s:.bshrc file. Of course, whichever pipe you use,
you will have to Mount it before using it; this should probably be
done in your startup-sequence.
If the pipe variable is set, bsh will run pipe segments in the
background as separate processes, if they are external commands.
This allows the pipe reader to start execution as soon as the pipe
feeder produces some output instead of waiting for it to complete.
As of version 1.0, a script which is executed as a pipe feeder,
will be run in a sub-shell in the background; this is also true
for a script run by the background operator '&'.
% script1 | wc Script1 runs in a subshell in the
background, while wc counts its
output.
% script1 & Script1 just runs in the background.
It is now possible to redirect standard input and standard output
to any file opened with the open() function. For example:
% j=open("foo","w")
% cmd >&$j
% close $j
The output from cmd has been placed in file foo just as if you had
typed:
% cmd >foo
Output can be appended to the end of a file by using the append
redirection operator:
% cmd >>foo
The standard error file can can be redirected for internal bsh
commands only (bsh will redirect standard error for external
commands when running under AmigaDOS2.0 or higher. Even then,
this will only work for those commands which check for DOS2.0 and
the pr_CES field in the process structure.)
% cmd 2>foo Redirect error messages from cmd to
file foo.
% cmd1 2>>foo Appends error messages to the end of
file foo.
% cmd1 2>&1 | cmd2 Sends error messages down the pipe
along with regular output.
A special form of input-file redirection is the here document;
this allows you to include data for a program in a script
immediately following the command invocation:
% prog <<some-string-of-your-choice
this is data line 1
this is data line 2
...
some-string-of-your-choice
The lines of data are copied to a ram: temporary file, and input
is redirected from that file.
7-0 SCRIPT PROGRAMMING
Scripts are run as any other command, that is, if you type "foo",
and the script file foo exists in your current directory or your
search path, it is run automatically as though you had typed
"source foo". For this "automatic sourcing" to occur, the script
file must have the SCRIPT and EXECUTE permission bits set:
% protect foo +se
You can also input or output redirect scripts the same as any
other program. Script output may also be piped to a different
program, however currently, the script does not run in parallel
and the pipe is a temporary ram: file. In version 1.0 of bsh,
these scripts will run in parallel in a separate shell.
Parameters may be passed to scripts and are available to the
script program in the local array argv. Argv[0] contains the
script name, and the remaining elements contain the actual
parameters.
7-1 LOOPING
Looping in scripts is accomplished using the WHILE or GOTO
commands.
Example:
i = 1
while i < 99
cmd1
if whatever
break
endif
i++
endwhile
Bsh branches within scripts by Seeking to the new location.
Because bsh cannot currently seek to the middle of a line, the
WHILE and LABEL commands must be the first command on a line.
Small loops (less than 1024 bytes) can be fit in a buffer and thus
eliminate disk thrashing.
7-2 ARGUMENT PASSING
Arguments are passed to scripts in the argv array variable. This
variable is local to the called script and is always an array,
even if no arguments were specified. Argv[0] contains the script
name, as specified on the command line. The remaining arguments
are in argv[1] thru argv[n], where n is the number of arguments.
The first ten arguments can be referenced in a short-hand way; $0
refers to $argv[0], $9 refers to $argv[9]. The notation $* refers
to all arguments after the script name, that is: $argv[1] ...
$argv[n]. $argv[*] refers to all arguments including the script
name, that is: $argv[0] ... $argv[n].
The argv array is only a copy of the strings passed to the script,
so you can safely alter elements of the array or even UNSET the
array.
The following program fragment shows how a script might examine its
arguments looking for keywords.
i = 1, list = 0, delete = 0, move = 0
while i < #argv
if lower(argv[i]) == 'list'
list = 1
elseif lower(argv[i]) == 'delete'
delete = 1
elseif lower(argv[i]) == 'move'
move = 1
endif
i++
endwhile
7-3 EXCEPTION PROCESSING and INTERRUPTS
If no onerr variable exists, any command which fails causes the
script to abort as though a RETURN command had been executed. A
command fails if its exit status is >= the FailLevel set by the
FailAt command. The script will then return that value as its own
exit status. The onerr variable is set by the ONERR command:
% onerr "stt=status,err=errno; cmd1; cmd2..."
While bsh is executing a script, if a command fails with
exit-status >= FailLevel, bsh then checks for the onerr variable.
If the onerr variable exists, then the error status is cleared and
the commands specified in the onerr variable are executed;
execution then resumes with the next command unless the onerr
contained a GOTO, RETURN or ABORT command. The ABORT command can
restore the exit-status:
% onerr "stt=status,err=errno; cmd1; cmd2...; abort $stt $err"
While bsh is executing a script, if a ^C (control-C) or ^D
(control-D) signal is received, bsh then checks for the onintr
variable (the onintr variable is set by the ONINTR command). If
the onintr variable exists, then the signals are cleared, and the
commands specified in the onintr variable are executed; execution
then resumes with the next command unless the onintr contained a
GOTO, RETURN or ABORT command.
Each script has its own onerr, and onintr variables; thus they can
safely reference labels in the script file.
The onerr/onintr commands should probably include one of RETURN or
GOTO or ABORT. This will ensure that an error in a pipe-line
causes the pipe-line to be aborted.
8-0 DIRECTORY ALIASES
Any argument of a command can make use of the directory alias
feature. To use this, the argument must start with one of the
directory aliases:
. the current directory.
.. the parent directory of the current dir.
./foo the file 'foo' in the current directory.
../foo the file 'foo' in the parent of the current dir.
~ the home dir (specified by the home variable).
~/foo the file 'foo' in the home dir.
The ../ operator may be applied repetitively to higher and higher
levels until you reach the root of a device:
../../f the file 'f' in the parent of the parent of the
current dir.
~/../f the file 'f' in the parent of the home dir.
All of the directory alias substitutions are replaced with
absolute path names; if you are currently in fred:a/b/c:
% echo ../../foo
fred:a/foo
% echo //foo
//foo
9-0 PROBLEMS
Do not redirect the RUN command. to redirect the command the RUN
command is running, include a standard CLI redirection in the
command string:
% RUN "command >file"
--------
You need to give bsh sufficient stack space, especially if you
will be running recursive shell scripts. 8192 is sufficient
for the maximum recursion depth (16). Stack should be run BEFORE
invoking bsh. Running it from within bsh does not affect bsh's
stack size. You don't need to worry about stack for newbsh, if
called from a CLI; in this case newbsh allocates a stack of 8192
bytes for itself. Stacksize set in newbsh tool icons or script
project icons should be set to at least 8192.
--------
Programs which use Manx or Lattice stdio can sometimes cause the
conman PIP: pipe-handler to crash. This is NOT a bug in bsh.
You can ignore the requester and the next time you use a pipe,
the PIP: pipe-handler will be reloaded.
--------
There is a bug in the new, DOS 2.04, Queue-Handler (V37 PIPE)
which causes the pipe writer program to hang if the the pipe
reader completes first. To see this try:
% mount PIPE:
% set pipe PIPE:
% type <some-file-bigger-than-12k> | More
when More starts up, type q (for quit). You will now have a
hung process "type" which bsh is waiting to complete. If you
type a ^E (control-E), you should see a line that looks like:
wait proc: type, procno 1, level 1
If you type a ^F (control-F), bsh will move that process (and all
others that it is waiting on) to the background, and once again
accept command input. If you execute the FILES command you should
see a line that looks like:
FILE: 3, 7EXXXXX/1FXXXXX, name = PIPE:A123456789, Write
Now type:
% cat PIPE:A123456789 >NIL:
The background "type" process should complete and go away. As an
alternative to this process, you could continue to use the V36
PIPE (Pipe-Handler); in your mountlist change L:Queue-Handler to
L:Pipe-Handler, and change Stacksize = 3000 to Stacksize = 6000.
If you updated from V36 to V37 using the 2.04 install disk, you
should find Pipe-Handler in the System2.0:old directory.
--------
Conman CNC: and CND: handlers apparently discard type-ahead when
bsh toggles in and out of raw mode. If type-ahead is important
to you, use regular CON: or NEWCON: console windows. Alternately,
if you want to use Conman features, use the -a option when starting
bsh or newbsh; this will disable the switch to raw mode.
--------
"Say" does something funky to the console after which, it is
impossible to place it in raw mode. This has the effect of making
bsh appear to hang. You can escape by typing a ^\ (control-\) to
get out of bsh. If you started by bsh (not newbsh), you should
EndCLI this CLI, as other programs which need to place the console
in raw mode will hang.
--------
It is not possible, currently, to redirect a parameterized alias
which contains pipe segments. That is
% alias lx "ls $! | grep -v \.info"
% lx >foo
will now get error 904: redirection error.
--------
Bsh does not run under AmigaDOS1.1 or older systems; bsh uses
several Exec, DOS, and Intuition library calls new to the 1.2 OS
release. If there is a great deal of interest in this, I may
provide a DOS1.1 compatible version. But this would be very
difficult as the Manx SDB debugger also does not run under
DOS1.1. Why are you running DOS1.1 anyway? This version is
obsolete.