1 /***********************************************************************
2 * *
3 * This software is part of the ast package *
4 * Copyright (c) 1982-2014 AT&T Intellectual Property *
5 * and is licensed under the *
6 * Eclipse Public License, Version 1.0 *
7 * by AT&T Intellectual Property *
8 * *
9 * A copy of the License is available at *
10 * http://www.eclipse.org/org/documents/epl-v10.html *
11 * (with md5 checksum b35adb5213ca9657e911e9befb180842) *
12 * *
13 * Information and Software Systems Research *
14 * AT&T Research *
15 * Florham Park NJ *
16 * *
17 * David Korn <dgkorn@gmail.com> *
18 * *
19 ***********************************************************************/
20 #include "config_ast.h" // IWYU pragma: keep
21
22 #include <stdbool.h>
23 #include <stdlib.h>
24
25 #include "builtins.h"
26 #include "cdt.h"
27 #include "defs.h"
28 #include "name.h"
29 #include "optget_long.h"
30 #include "shcmd.h"
31
32 static const char *short_options = "+:fnv";
33 static const struct optget_option long_options[] = {
34 {"help", optget_no_arg, NULL, 1}, // all builtins support --help
35 {NULL, 0, NULL, 0}};
36
37 //
38 // The `unset` builtin.
39 //
b_unset(int argc,char * argv[],Shbltin_t * context)40 int b_unset(int argc, char *argv[], Shbltin_t *context) {
41 Shell_t *shp = context->shp;
42 char *cmd = argv[0];
43 Dt_t *troot = shp->var_tree;
44 nvflag_t nvflags = 0;
45 int opt;
46
47 optget_ind = 0;
48 while ((opt = optget_long(argc, argv, short_options, long_options)) != -1) {
49 switch (opt) {
50 case 1: {
51 builtin_print_help(shp, cmd);
52 return 0;
53 }
54 case 'f': {
55 troot = sh_subfuntree(shp, true);
56 nvflags |= NV_NOSCOPE;
57 break;
58 }
59 case 'n': {
60 nvflags |= NV_NOREF;
61 troot = shp->var_tree;
62 break;
63 }
64 case 'v': {
65 troot = shp->var_tree;
66 break;
67 }
68 case ':': {
69 builtin_missing_argument(shp, cmd, argv[optget_ind - 1]);
70 return 2;
71 }
72 case '?': {
73 builtin_unknown_option(shp, cmd, argv[optget_ind - 1]);
74 return 2;
75 }
76 default: { abort(); }
77 }
78 }
79 argv += optget_ind;
80
81 if (!*argv) {
82 builtin_usage_error(shp, cmd, "expected at least one variable or function name");
83 return 2;
84 }
85
86 if (!troot) return 1;
87 if (troot == shp->var_tree) nvflags |= NV_VARNAME;
88 return nv_unall(argv, false, nvflags, troot, shp);
89 }
90