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