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