1shell(3) Erlang Module Definition shell(3)
2
3
4
6 shell - The Erlang shell.
7
9 This module provides an Erlang shell.
10
11 The shell is a user interface program for entering expression
12 sequences. The expressions are evaluated and a value is returned. A
13 history mechanism saves previous commands and their values, which can
14 then be incorporated in later commands. How many commands and results
15 to save can be determined by the user, either interactively, by calling
16 history/1 and results/1, or by setting the application configuration
17 parameters shell_history_length and shell_saved_results for the STDLIB
18 application.
19
20 The shell uses a helper process for evaluating commands to protect the
21 history mechanism from exceptions. By default the evaluator process is
22 killed when an exception occurs, but by calling catch_exception/1 or by
23 setting the application configuration parameter shell_catch_exception
24 for the STDLIB application this behavior can be changed. See also the
25 example below.
26
27 Variable bindings, and local process dictionary changes that are gener‐
28 ated in user expressions are preserved, and the variables can be used
29 in later commands to access their values. The bindings can also be for‐
30 gotten so the variables can be reused.
31
32 The special shell commands all have the syntax of (local) function
33 calls. They are evaluated as normal function calls and many commands
34 can be used in one expression sequence.
35
36 If a command (local function call) is not recognized by the shell, an
37 attempt is first made to find the function in module user_default,
38 where customized local commands can be placed. If found, the function
39 is evaluated, otherwise an attempt is made to evaluate the function in
40 module shell_default. Module user_default must be explicitly loaded.
41
42 The shell also permits the user to start multiple concurrent jobs. A
43 job can be regarded as a set of processes that can communicate with the
44 shell.
45
46 There is some support for reading and printing records in the shell.
47 During compilation record expressions are translated to tuple expres‐
48 sions. In runtime it is not known whether a tuple represents a record,
49 and the record definitions used by the compiler are unavailable at run‐
50 time. So, to read the record syntax and print tuples as records when
51 possible, record definitions must be maintained by the shell itself.
52
53 The shell commands for reading, defining, forgetting, listing, and
54 printing records are described below. Notice that each job has its own
55 set of record definitions. To facilitate matters, record definitions in
56 modules shell_default and user_default (if loaded) are read each time a
57 new job is started. For example, adding the following line to
58 user_default makes the definition of file_info readily available in the
59 shell:
60
61 -include_lib("kernel/include/file.hrl").
62
63 The shell runs in two modes:
64
65 * Normal (possibly restricted) mode, in which commands can be edited
66 and expressions evaluated
67
68 * Job Control Mode, JCL, in which jobs can be started, killed,
69 detached, and connected
70
71 Only the currently connected job can 'talk' to the shell.
72
74 b():
75 Prints the current variable bindings.
76
77 f():
78 Removes all variable bindings.
79
80 f(X):
81 Removes the binding of variable X.
82
83 h():
84 Prints the history list.
85
86 history(N):
87 Sets the number of previous commands to keep in the history list to
88 N. The previous number is returned. Defaults to 20.
89
90 results(N):
91 Sets the number of results from previous commands to keep in the
92 history list to N. The previous number is returned. Defaults to 20.
93
94 e(N):
95 Repeats command N, if N is positive. If it is negative, the Nth
96 previous command is repeated (that is, e(-1) repeats the previous
97 command).
98
99 v(N):
100 Uses the return value of command N in the current command, if N is
101 positive. If it is negative, the return value of the Nth previous
102 command is used (that is, v(-1) uses the value of the previous com‐
103 mand).
104
105 help():
106 Evaluates shell_default:help().
107
108 c(Mod):
109 Evaluates shell_default:c(Mod). This compiles and loads the module
110 Mod and purges old versions of the code, if necessary. Mod can be
111 either a module name or a a source file path, with or without .erl
112 extension.
113
114 catch_exception(Bool):
115 Sets the exception handling of the evaluator process. The previous
116 exception handling is returned. The default (false) is to kill the
117 evaluator process when an exception occurs, which causes the shell
118 to create a new evaluator process. When the exception handling is
119 set to true, the evaluator process lives on. This means, for exam‐
120 ple, that ports and ETS tables as well as processes linked to the
121 evaluator process survive the exception.
122
123 rd(RecordName, RecordDefinition):
124 Defines a record in the shell. RecordName is an atom and RecordDef‐
125 inition lists the field names and the default values. Usually
126 record definitions are made known to the shell by use of the
127 rr/1,2,3 commands described below, but sometimes it is handy to
128 define records on the fly.
129
130 rf():
131 Removes all record definitions, then reads record definitions from
132 the modules shell_default and user_default (if loaded). Returns the
133 names of the records defined.
134
135 rf(RecordNames):
136 Removes selected record definitions. RecordNames is a record name
137 or a list of record names. To remove all record definitions, use
138 '_'.
139
140 rl():
141 Prints all record definitions.
142
143 rl(RecordNames):
144 Prints selected record definitions. RecordNames is a record name or
145 a list of record names.
146
147 rp(Term):
148 Prints a term using the record definitions known to the shell. All
149 of Term is printed; the depth is not limited as is the case when a
150 return value is printed.
151
152 rr(Module):
153 Reads record definitions from a module's BEAM file. If there are no
154 record definitions in the BEAM file, the source file is located and
155 read instead. Returns the names of the record definitions read.
156 Module is an atom.
157
158 rr(Wildcard):
159 Reads record definitions from files. Existing definitions of any of
160 the record names read are replaced. Wildcard is a wildcard string
161 as defined in filelib(3), but not an atom.
162
163 rr(WildcardOrModule, RecordNames):
164 Reads record definitions from files but discards record names not
165 mentioned in RecordNames (a record name or a list of record names).
166
167 rr(WildcardOrModule, RecordNames, Options):
168 Reads record definitions from files. The compiler options {i, Dir},
169 {d, Macro}, and {d, Macro, Value} are recognized and used for set‐
170 ting up the include path and macro definitions. To read all record
171 definitions, use '_' as value of RecordNames.
172
174 The following example is a long dialog with the shell. Commands start‐
175 ing with > are inputs to the shell. All other lines are output from the
176 shell.
177
178 strider 1> erl
179 Erlang (BEAM) emulator version 5.3 [hipe] [threads:0]
180
181 Eshell V5.3 (abort with ^G)
182 1> Str = "abcd".
183 "abcd"
184
185 Command 1 sets variable Str to string "abcd".
186
187 2> L = length(Str).
188 4
189
190 Command 2 sets L to the length of string Str.
191
192 3> Descriptor = {L, list_to_atom(Str)}.
193 {4,abcd}
194
195 Command 3 builds the tuple Descriptor, evaluating the BIF
196 list_to_atom/1.
197
198 4> L.
199 4
200
201 Command 4 prints the value of variable L.
202
203 5> b().
204 Descriptor = {4,abcd}
205 L = 4
206 Str = "abcd"
207 ok
208
209 Command 5 evaluates the internal shell command b(), which is an abbre‐
210 viation of "bindings". This prints the current shell variables and
211 their bindings. ok at the end is the return value of function b().
212
213 6> f(L).
214 ok
215
216 Command 6 evaluates the internal shell command f(L) (abbreviation of
217 "forget"). The value of variable L is removed.
218
219 7> b().
220 Descriptor = {4,abcd}
221 Str = "abcd"
222 ok
223
224 Command 7 prints the new bindings.
225
226 8> f(L).
227 ok
228
229 Command 8 has no effect, as L has no value.
230
231 9> {L, _} = Descriptor.
232 {4,abcd}
233
234 Command 9 performs a pattern matching operation on Descriptor, binding
235 a new value to L.
236
237 10> L.
238 4
239
240 Command 10 prints the current value of L.
241
242 11> {P, Q, R} = Descriptor.
243 ** exception error: no match of right hand side value {4,abcd}
244
245 Command 11 tries to match {P, Q, R} against Descriptor, which is {4,
246 abc}. The match fails and none of the new variables become bound. The
247 printout starting with "** exception error:" is not the value of the
248 expression (the expression had no value because its evaluation failed),
249 but a warning printed by the system to inform the user that an error
250 has occurred. The values of the other variables (L, Str, and so on) are
251 unchanged.
252
253 12> P.
254 * 1: variable 'P' is unbound
255 13> Descriptor.
256 {4,abcd}
257
258 Commands 12 and 13 show that P is unbound because the previous command
259 failed, and that Descriptor has not changed.
260
261 14>{P, Q} = Descriptor.
262 {4,abcd}
263 15> P.
264 4
265
266 Commands 14 and 15 show a correct match where P and Q are bound.
267
268 16> f().
269 ok
270
271 Command 16 clears all bindings.
272
273 The next few commands assume that test1:demo(X) is defined as follows:
274
275 demo(X) ->
276 put(aa, worked),
277 X = 1,
278 X + 10.
279
280 17> put(aa, hello).
281 undefined
282 18> get(aa).
283 hello
284
285 Commands 17 and 18 set and inspect the value of item aa in the process
286 dictionary.
287
288 19> Y = test1:demo(1).
289 11
290
291 Command 19 evaluates test1:demo(1). The evaluation succeeds and the
292 changes made in the process dictionary become visible to the shell. The
293 new value of dictionary item aa can be seen in command 20.
294
295 20> get().
296 [{aa,worked}]
297 21> put(aa, hello).
298 worked
299 22> Z = test1:demo(2).
300 ** exception error: no match of right hand side value 1
301 in function test1:demo/1
302
303 Commands 21 and 22 change the value of dictionary item aa to hello and
304 call test1:demo(2). Evaluation fails and the changes made to the dic‐
305 tionary in test1:demo(2), before the error occurred, are discarded.
306
307 23> Z.
308 * 1: variable 'Z' is unbound
309 24> get(aa).
310 hello
311
312 Commands 23 and 24 show that Z was not bound and that dictionary item
313 aa has retained its original value.
314
315 25> erase(), put(aa, hello).
316 undefined
317 26> spawn(test1, demo, [1]).
318 <0.57.0>
319 27> get(aa).
320 hello
321
322 Commands 25, 26, and 27 show the effect of evaluating test1:demo(1) in
323 the background. In this case, the expression is evaluated in a newly
324 spawned process. Any changes made in the process dictionary are local
325 to the newly spawned process and therefore not visible to the shell.
326
327 28> io:format("hello hello\n").
328 hello hello
329 ok
330 29> e(28).
331 hello hello
332 ok
333 30> v(28).
334 ok
335
336 Commands 28, 29 and 30 use the history facilities of the shell. Command
337 29 re-evaluates command 28. Command 30 uses the value (result) of com‐
338 mand 28. In the cases of a pure function (a function with no side
339 effects), the result is the same. For a function with side effects, the
340 result can be different.
341
342 The next few commands show some record manipulation. It is assumed that
343 ex.erl defines a record as follows:
344
345 -record(rec, {a, b = val()}).
346
347 val() ->
348 3.
349
350 31> c(ex).
351 {ok,ex}
352 32> rr(ex).
353 [rec]
354
355 Commands 31 and 32 compile file ex.erl and read the record definitions
356 in ex.beam. If the compiler did not output any record definitions on
357 the BEAM file, rr(ex) tries to read record definitions from the source
358 file instead.
359
360 33> rl(rec).
361 -record(rec,{a,b = val()}).
362 ok
363
364 Command 33 prints the definition of the record named rec.
365
366 34> #rec{}.
367 ** exception error: undefined shell command val/0
368
369 Command 34 tries to create a rec record, but fails as function val/0 is
370 undefined.
371
372 35> #rec{b = 3}.
373 #rec{a = undefined,b = 3}
374
375 Command 35 shows the workaround: explicitly assign values to record
376 fields that cannot otherwise be initialized.
377
378 36> rp(v(-1)).
379 #rec{a = undefined,b = 3}
380 ok
381
382 Command 36 prints the newly created record using record definitions
383 maintained by the shell.
384
385 37> rd(rec, {f = orddict:new()}).
386 rec
387
388 Command 37 defines a record directly in the shell. The definition
389 replaces the one read from file ex.beam.
390
391 38> #rec{}.
392 #rec{f = []}
393 ok
394
395 Command 38 creates a record using the new definition, and prints the
396 result.
397
398 39> rd(rec, {c}), A.
399 * 1: variable 'A' is unbound
400 40> #rec{}.
401 #rec{c = undefined}
402 ok
403
404 Command 39 and 40 show that record definitions are updated as side
405 effects. The evaluation of the command fails, but the definition of rec
406 has been carried out.
407
408 For the next command, it is assumed that test1:loop(N) is defined as
409 follows:
410
411 loop(N) ->
412 io:format("Hello Number: ~w~n", [N]),
413 loop(N+1).
414
415 41> test1:loop(0).
416 Hello Number: 0
417 Hello Number: 1
418 Hello Number: 2
419 Hello Number: 3
420
421 User switch command
422 --> i
423 --> c
424 Hello Number: 3374
425 Hello Number: 3375
426 Hello Number: 3376
427 Hello Number: 3377
428 Hello Number: 3378
429 ** exception exit: killed
430
431 Command 41 evaluates test1:loop(0), which puts the system into an infi‐
432 nite loop. At this point the user types ^G (Control G), which suspends
433 output from the current process, which is stuck in a loop, and acti‐
434 vates JCL mode. In JCL mode the user can start and stop jobs.
435
436 In this particular case, command i ("interrupt") terminates the looping
437 program, and command c connects to the shell again. As the process was
438 running in the background before we killed it, more printouts occur
439 before message "** exception exit: killed" is shown.
440
441 42> E = ets:new(t, []).
442 #Ref<0.1662103692.2407923716.214192>
443
444 Command 42 creates an ETS table.
445
446 43> ets:insert({d,1,2}).
447 ** exception error: undefined function ets:insert/1
448
449 Command 43 tries to insert a tuple into the ETS table, but the first
450 argument (the table) is missing. The exception kills the evaluator
451 process.
452
453 44> ets:insert(E, {d,1,2}).
454 ** exception error: argument is of wrong type
455 in function ets:insert/2
456 called as ets:insert(16,{d,1,2})
457
458 Command 44 corrects the mistake, but the ETS table has been destroyed
459 as it was owned by the killed evaluator process.
460
461 45> f(E).
462 ok
463 46> catch_exception(true).
464 false
465
466 Command 46 sets the exception handling of the evaluator process to
467 true. The exception handling can also be set when starting Erlang by
468 erl -stdlib shell_catch_exception true.
469
470 47> E = ets:new(t, []).
471 #Ref<0.1662103692.2407923716.214197>
472 48> ets:insert({d,1,2}).
473 * exception error: undefined function ets:insert/1
474
475 Command 48 makes the same mistake as in command 43, but this time the
476 evaluator process lives on. The single star at the beginning of the
477 printout signals that the exception has been caught.
478
479 49> ets:insert(E, {d,1,2}).
480 true
481
482 Command 49 successfully inserts the tuple into the ETS table.
483
484 50> ets:insert(#Ref<0.1662103692.2407923716.214197>, {e,3,4}).
485 true
486
487 Command 50 inserts another tuple into the ETS table. This time the
488 first argument is the table identifier itself. The shell can parse com‐
489 mands with pids (<0.60.0>), ports (#Port<0.536>), references
490 (#Ref<0.1662103692.2407792644.214210>), and external functions
491 (#Fun<a.b.1>), but the command fails unless the corresponding pid,
492 port, reference, or function can be created in the running system.
493
494 51> halt().
495 strider 2>
496
497 Command 51 exits the Erlang runtime system.
498
500 When the shell starts, it starts a single evaluator process. This
501 process, together with any local processes that it spawns, is referred
502 to as a job. Only the current job, which is said to be connected, can
503 perform operations with standard I/O. All other jobs, which are said to
504 be detached, are blocked if they attempt to use standard I/O.
505
506 All jobs that do not use standard I/O run in the normal way.
507
508 The shell escape key ^G (Control G) detaches the current job and acti‐
509 vates JCL mode. The JCL mode prompt is "-->". If "?" is entered at the
510 prompt, the following help message is displayed:
511
512 --> ?
513 c [nn] - connect to job
514 i [nn] - interrupt job
515 k [nn] - kill job
516 j - list all jobs
517 s [shell] - start local shell
518 r [node [shell]] - start remote shell
519 q - quit erlang
520 ? | h - this message
521
522 The JCL commands have the following meaning:
523
524 c [nn]:
525 Connects to job number <nn> or the current job. The standard shell
526 is resumed. Operations that use standard I/O by the current job are
527 interleaved with user inputs to the shell.
528
529 i [nn]:
530 Stops the current evaluator process for job number nn or the cur‐
531 rent job, but does not kill the shell process. So, any variable
532 bindings and the process dictionary are preserved and the job can
533 be connected again. This command can be used to interrupt an end‐
534 less loop.
535
536 k [nn]:
537 Kills job number nn or the current job. All spawned processes in
538 the job are killed, provided they have not evaluated the
539 group_leader/1 BIF and are located on the local machine. Processes
540 spawned on remote nodes are not killed.
541
542 j:
543 Lists all jobs. A list of all known jobs is printed. The current
544 job name is prefixed with '*'.
545
546 s:
547 Starts a new job. This is assigned the new index [nn], which can be
548 used in references.
549
550 s [shell]:
551 Starts a new job. This is assigned the new index [nn], which can be
552 used in references. If optional argument shell is specified, it is
553 assumed to be a module that implements an alternative shell.
554
555 r [node]:
556 Starts a remote job on node. This is used in distributed Erlang to
557 allow a shell running on one node to control a number of applica‐
558 tions running on a network of nodes. If optional argument shell is
559 specified, it is assumed to be a module that implements an alterna‐
560 tive shell.
561
562 q:
563 Quits Erlang. Notice that this option is disabled if Erlang is
564 started with the ignore break, +Bi, system flag (which can be use‐
565 ful, for example when running a restricted shell, see the next sec‐
566 tion).
567
568 ?:
569 Displays the help message above.
570
571 The behavior of shell escape can be changed by the STDLIB application
572 variable shell_esc. The value of the variable can be either jcl (erl
573 -stdlib shell_esc jcl) or abort (erl -stdlib shell_esc abort). The
574 first option sets ^G to activate JCL mode (which is also default behav‐
575 ior). The latter sets ^G to terminate the current shell and start a new
576 one. JCL mode cannot be invoked when shell_esc is set to abort.
577
578 If you want an Erlang node to have a remote job active from the start
579 (rather than the default local job), start Erlang with flag -remsh, for
580 example, erl -sname this_node -remsh other_node@other_host
581
583 The shell can be started in a restricted mode. In this mode, the shell
584 evaluates a function call only if allowed. This feature makes it possi‐
585 ble to, for example, prevent a user from accidentally calling a func‐
586 tion from the prompt that could harm a running system (useful in combi‐
587 nation with system flag +Bi).
588
589 When the restricted shell evaluates an expression and encounters a
590 function call or an operator application, it calls a callback function
591 (with information about the function call in question). This callback
592 function returns true to let the shell go ahead with the evaluation, or
593 false to abort it. There are two possible callback functions for the
594 user to implement:
595
596 * local_allowed(Func, ArgList, State) -> {boolean(),NewState}
597
598 This is used to determine if the call to the local function Func
599 with arguments ArgList is to be allowed.
600
601 * non_local_allowed(FuncSpec, ArgList, State) -> {boolean(),NewState}
602 | {{redirect,NewFuncSpec,NewArgList},NewState}
603
604 This is used to determine if the call to non-local function Func‐
605 Spec ({Module,Func} or a fun) with arguments ArgList is to be
606 allowed. The return value {redirect,NewFuncSpec,NewArgList} can be
607 used to let the shell evaluate some other function than the one
608 specified by FuncSpec and ArgList.
609
610 These callback functions are called from local and non-local evaluation
611 function handlers, described in the erl_eval manual page. (Arguments in
612 ArgList are evaluated before the callback functions are called.)
613
614 Argument State is a tuple {ShellState,ExprState}. The return value New‐
615 State has the same form. This can be used to carry a state between
616 calls to the callback functions. Data saved in ShellState lives through
617 an entire shell session. Data saved in ExprState lives only through the
618 evaluation of the current expression.
619
620 There are two ways to start a restricted shell session:
621
622 * Use STDLIB application variable restricted_shell and specify, as
623 its value, the name of the callback module. Example (with callback
624 functions implemented in callback_mod.erl): $ erl -stdlib
625 restricted_shell callback_mod.
626
627 * From a normal shell session, call function start_restricted/1. This
628 exits the current evaluator and starts a new one in restricted
629 mode.
630
631 Notes:
632
633 * When restricted shell mode is activated or deactivated, new jobs
634 started on the node run in restricted or normal mode, respectively.
635
636 * If restricted mode has been enabled on a particular node, remote
637 shells connecting to this node also run in restricted mode.
638
639 * The callback functions cannot be used to allow or disallow execu‐
640 tion of functions called from compiled code (only functions called
641 from expressions entered at the shell prompt).
642
643 Errors when loading the callback module is handled in different ways
644 depending on how the restricted shell is activated:
645
646 * If the restricted shell is activated by setting the STDLIB variable
647 during emulator startup, and the callback module cannot be loaded,
648 a default restricted shell allowing only the commands q() and
649 init:stop() is used as fallback.
650
651 * If the restricted shell is activated using start_restricted/1 and
652 the callback module cannot be loaded, an error report is sent to
653 the error logger and the call returns {error,Reason}.
654
656 The default shell prompt function displays the name of the node (if the
657 node can be part of a distributed system) and the current command num‐
658 ber. The user can customize the prompt function by calling
659 prompt_func/1 or by setting application configuration parameter
660 shell_prompt_func for the STDLIB application.
661
662 A customized prompt function is stated as a tuple {Mod, Func}. The
663 function is called as Mod:Func(L), where L is a list of key-value pairs
664 created by the shell. Currently there is only one pair: {history, N},
665 where N is the current command number. The function is to return a list
666 of characters or an atom. This constraint is because of the Erlang I/O
667 protocol. Unicode characters beyond code point 255 are allowed in the
668 list and the atom. Notice that in restricted mode the call Mod:Func(L)
669 must be allowed or the default shell prompt function is called.
670
672 catch_exception(Bool) -> boolean()
673
674 Types:
675
676 Bool = boolean()
677
678 Sets the exception handling of the evaluator process. The previ‐
679 ous exception handling is returned. The default (false) is to
680 kill the evaluator process when an exception occurs, which
681 causes the shell to create a new evaluator process. When the
682 exception handling is set to true, the evaluator process lives
683 on, which means that, for example, ports and ETS tables as well
684 as processes linked to the evaluator process survive the excep‐
685 tion.
686
687 history(N) -> integer() >= 0
688
689 Types:
690
691 N = integer() >= 0
692
693 Sets the number of previous commands to keep in the history list
694 to N. The previous number is returned. Defaults to 20.
695
696 prompt_func(PromptFunc) -> PromptFunc2
697
698 Types:
699
700 PromptFunc = PromptFunc2 = default | {module(), atom()}
701
702 Sets the shell prompt function to PromptFunc. The previous
703 prompt function is returned.
704
705 results(N) -> integer() >= 0
706
707 Types:
708
709 N = integer() >= 0
710
711 Sets the number of results from previous commands to keep in the
712 history list to N. The previous number is returned. Defaults to
713 20.
714
715 start_restricted(Module) -> {error, Reason}
716
717 Types:
718
719 Module = module()
720 Reason = code:load_error_rsn()
721
722 Exits a normal shell and starts a restricted shell. Module spec‐
723 ifies the callback module for the functions local_allowed/3 and
724 non_local_allowed/3. The function is meant to be called from the
725 shell.
726
727 If the callback module cannot be loaded, an error tuple is
728 returned. The Reason in the error tuple is the one returned by
729 the code loader when trying to load the code of the callback
730 module.
731
732 stop_restricted() -> no_return()
733
734 Exits a restricted shell and starts a normal shell. The function
735 is meant to be called from the shell.
736
737 strings(Strings) -> Strings2
738
739 Types:
740
741 Strings = Strings2 = boolean()
742
743 Sets pretty printing of lists to Strings. The previous value of
744 the flag is returned.
745
746 The flag can also be set by the STDLIB application variable
747 shell_strings. Defaults to true, which means that lists of inte‐
748 gers are printed using the string syntax, when possible. Value
749 false means that no lists are printed using the string syntax.
750
751
752
753Ericsson AB stdlib 3.8.2.1 shell(3)