-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyshell.c
More file actions
1970 lines (1670 loc) · 57.6 KB
/
Copy pathmyshell.c
File metadata and controls
1970 lines (1670 loc) · 57.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <fcntl.h>
#include <signal.h>
#include <dirent.h>
#include <termios.h>
#include <ctype.h>
#include <sys/time.h>
#include <time.h>
#define MAX_INPUT 1024
#define MAX_ARGS 64
#define MAX_PIPES 10
#define MAX_COMPLETIONS 256
#define MAX_HISTORY 1000
#define MAX_ALIASES 100
#define MAX_BOOKMARKS 50
#define MAX_NOTES 200
// Terminal settings
struct termios orig_termios;
// Command history
char* history[MAX_HISTORY];
int history_count = 0;
int history_index = 0;
// Aliases
typedef struct {
char* name;
char* value;
} Alias;
Alias aliases[MAX_ALIASES];
int alias_count = 0;
// Directory bookmarks
typedef struct {
char* name;
char* path;
} Bookmark;
Bookmark bookmarks[MAX_BOOKMARKS];
int bookmark_count = 0;
// Function prototypes
void display_prompt();
char* read_input_with_completion();
char** parse_input(char* input);
int execute_command(char** args);
int execute_piped_commands(char** args);
void handle_redirection(char** args);
int builtin_cd(char** args);
int builtin_exit(char** args);
int builtin_help(char** args);
int builtin_alias(char** args);
int builtin_mark(char** args);
int builtin_jump(char** args);
int builtin_marks(char** args);
int builtin_unmark(char** args);
int builtin_note(char** args);
int builtin_notes(char** args);
int builtin_clearnotes(char** args);
int builtin_delnote(char** args);
int builtin_exec(char** args);
int builtin_source(char** args);
int builtin_type(char** args);
int is_arithmetic_expression(char* str);
double evaluate_expression(char* expr);
void load_myshellrc();
void add_alias(char* name, char* value);
char* get_alias(char* name);
char* expand_aliases(char* input);
void load_bookmarks();
void save_bookmarks();
void add_bookmark(char* name, char* path);
char* get_bookmark(char* name);
void save_note(char* note);
void display_notes();
char** get_completions(char* partial, int* count);
char** get_command_completions(char* partial, int* count);
char** get_file_completions(char* partial, int* count);
void enable_raw_mode();
void disable_raw_mode();
void add_to_history(char* cmd);
void save_history_to_file();
void load_history_from_file();
// Built-in command names
char* builtin_names[] = {
"cd",
"exit",
"help",
"alias",
"mark",
"jump",
"marks",
"unmark",
"note",
"notes",
"clearnotes",
"delnote",
"exec",
"source",
"type"
};
// Built-in command functions
int (*builtin_funcs[])(char**) = {
&builtin_cd,
&builtin_exit,
&builtin_help,
&builtin_alias,
&builtin_mark,
&builtin_jump,
&builtin_marks,
&builtin_unmark,
&builtin_note,
&builtin_notes,
&builtin_clearnotes,
&builtin_delnote,
&builtin_exec,
&builtin_source,
&builtin_type
};
int num_builtins() {
return sizeof(builtin_names) / sizeof(char*);
}
// Built-in: cd
int builtin_cd(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: expected argument to \"cd\"\n");
} else {
if (chdir(args[1]) != 0) {
perror("myshell");
}
}
return 1;
}
// Built-in: exit
int builtin_exit(char** args) {
return 0;
}
// Built-in: help
int builtin_help(char** args) {
printf("MyShell - A Simple Unix Shell\n");
printf("Type program names and arguments, then press enter.\n");
printf("Built-in commands:\n");
for (int i = 0; i < num_builtins(); i++) {
printf(" %s\n", builtin_names[i]);
}
printf("\nFeatures:\n");
printf(" - Command execution\n");
printf(" - Input/Output redirection (< and >)\n");
printf(" - Piping (|)\n");
printf(" - Tab completion for commands and files\n");
printf(" - Command history with UP/DOWN arrows\n");
printf(" - Arithmetic evaluation (e.g., 2+3, 10*5, 100/4)\n");
printf(" - Cursor navigation with LEFT/RIGHT arrows\n");
printf(" - Word-by-word navigation with CTRL+LEFT/RIGHT\n");
printf(" - Double-tap ESC to add 'sudo' at the beginning!\n");
printf(" - Aliases support via ~/.myshellrc\n");
printf("\nKeyboard Shortcuts:\n");
printf(" - TAB: Auto-completion\n");
printf(" - UP/DOWN: Navigate history\n");
printf(" - LEFT/RIGHT: Move cursor character by character\n");
printf(" - CTRL+LEFT/RIGHT: Move cursor word by word\n");
printf(" - ESC ESC (double tap): Add 'sudo' at the beginning\n");
printf(" - BACKSPACE: Delete character before cursor\n");
printf(" - CTRL+D: Exit shell\n");
printf("\n~/.myshellrc Support:\n");
printf(" - alias name='command': Create command alias\n");
printf(" - export VAR=value: Set environment variable\n");
printf(" - # comments: Add comments\n");
printf("\nDirectory Bookmarks:\n");
printf(" - mark <name>: Bookmark current directory\n");
printf(" - jump <name>: Jump to bookmarked directory\n");
printf(" - marks: List all bookmarks\n");
printf(" - unmark <name>: Remove bookmark\n");
printf("\nSession Notes:\n");
printf(" - note <text>: Add a note\n");
printf(" - notes: View all notes\n");
printf(" - delnote <n>: Delete note number N\n");
printf(" - clearnotes: Clear all notes\n");
printf("\nAdvanced Commands:\n");
printf(" - exec <cmd>: Replace shell with command\n");
printf(" - source <file>: Execute commands from file\n");
printf(" - type <cmd>: Show command type and location\n");
return 1;
}
// Built-in: alias
int builtin_alias(char** args) {
if (args[1] == NULL) {
// List all aliases
if (alias_count == 0) {
printf("No aliases defined.\n");
} else {
for (int i = 0; i < alias_count; i++) {
printf("alias %s='%s'\n", aliases[i].name, aliases[i].value);
}
}
} else {
// Parse alias definition: alias name='value' or alias name=value
char* equal = strchr(args[1], '=');
if (equal) {
*equal = '\0';
char* name = args[1];
char* value = equal + 1;
// Remove quotes if present
if (value[0] == '\'' || value[0] == '"') {
value++;
int len = strlen(value);
if (len > 0 && (value[len-1] == '\'' || value[len-1] == '"')) {
value[len-1] = '\0';
}
}
add_alias(name, value);
printf("alias %s='%s'\n", name, value);
} else {
// Show specific alias
char* value = get_alias(args[1]);
if (value) {
printf("alias %s='%s'\n", args[1], value);
} else {
printf("myshell: alias: %s: not found\n", args[1]);
}
}
}
return 1;
}
// Add or update an alias
void add_alias(char* name, char* value) {
// Check if alias already exists
for (int i = 0; i < alias_count; i++) {
if (strcmp(aliases[i].name, name) == 0) {
free(aliases[i].value);
aliases[i].value = strdup(value);
return;
}
}
// Add new alias
if (alias_count < MAX_ALIASES) {
aliases[alias_count].name = strdup(name);
aliases[alias_count].value = strdup(value);
alias_count++;
} else {
fprintf(stderr, "myshell: maximum number of aliases reached\n");
}
}
// Get alias value
char* get_alias(char* name) {
for (int i = 0; i < alias_count; i++) {
if (strcmp(aliases[i].name, name) == 0) {
return aliases[i].value;
}
}
return NULL;
}
// Expand aliases in command
char* expand_aliases(char* input) {
static char expanded[MAX_INPUT * 2];
char* result = expanded;
char temp[MAX_INPUT];
strncpy(temp, input, MAX_INPUT);
// Get first word (command)
char* first_word = strtok(temp, " \t");
if (!first_word) {
return input;
}
// Check if it's an alias
char* alias_value = get_alias(first_word);
if (alias_value) {
// Replace with alias value
strcpy(result, alias_value);
// Add remaining arguments
char* rest = input + strlen(first_word);
if (*rest) {
strcat(result, rest);
}
return result;
}
return input;
}
// Load and execute .myshellrc
void load_myshellrc() {
char* home = getenv("HOME");
if (!home) return;
char filepath[1024];
snprintf(filepath, sizeof(filepath), "%s/.myshellrc", home);
FILE* f = fopen(filepath, "r");
if (!f) return;
printf("Loading ~/.myshellrc...\n");
char line[MAX_INPUT];
int line_num = 0;
while (fgets(line, sizeof(line), f)) {
line_num++;
// Remove newline
line[strcspn(line, "\n")] = 0;
// Skip empty lines and comments
char* trimmed = line;
while (*trimmed == ' ' || *trimmed == '\t') trimmed++;
if (*trimmed == '\0' || *trimmed == '#') continue;
// Handle alias definitions
if (strncmp(trimmed, "alias ", 6) == 0) {
char* alias_def = trimmed + 6;
char* equal = strchr(alias_def, '=');
if (equal) {
*equal = '\0';
char* name = alias_def;
char* value = equal + 1;
// Trim name
while (*name == ' ' || *name == '\t') name++;
char* name_end = name + strlen(name) - 1;
while (name_end > name && (*name_end == ' ' || *name_end == '\t')) {
*name_end = '\0';
name_end--;
}
// Remove quotes from value
while (*value == ' ' || *value == '\t') value++;
if (*value == '\'' || *value == '"') {
value++;
int len = strlen(value);
if (len > 0 && (value[len-1] == '\'' || value[len-1] == '"')) {
value[len-1] = '\0';
}
}
add_alias(name, value);
}
}
// Handle export statements
else if (strncmp(trimmed, "export ", 7) == 0) {
char* export_def = trimmed + 7;
char* equal = strchr(export_def, '=');
if (equal) {
*equal = '\0';
char* name = export_def;
char* value = equal + 1;
// Trim name
while (*name == ' ' || *name == '\t') name++;
// Remove quotes from value
while (*value == ' ' || *value == '\t') value++;
if (*value == '\'' || *value == '"') {
value++;
int len = strlen(value);
if (len > 0 && (value[len-1] == '\'' || value[len-1] == '"')) {
value[len-1] = '\0';
}
}
setenv(name, value, 1);
}
}
// Execute other commands (like echo)
else {
char** args = parse_input(strdup(line));
if (args[0] != NULL) {
execute_command(args);
}
free(args);
}
}
fclose(f);
printf("Loaded %d aliases from ~/.myshellrc\n", alias_count);
}
// Directory Bookmarks Functions
// Load bookmarks from file
void load_bookmarks() {
char* home = getenv("HOME");
if (!home) return;
char filepath[1024];
snprintf(filepath, sizeof(filepath), "%s/.myshell_bookmarks", home);
FILE* f = fopen(filepath, "r");
if (!f) return;
char line[MAX_INPUT];
while (fgets(line, sizeof(line), f) && bookmark_count < MAX_BOOKMARKS) {
line[strcspn(line, "\n")] = 0;
char* sep = strchr(line, ':');
if (sep) {
*sep = '\0';
bookmarks[bookmark_count].name = strdup(line);
bookmarks[bookmark_count].path = strdup(sep + 1);
bookmark_count++;
}
}
fclose(f);
}
// Save bookmarks to file
void save_bookmarks() {
char* home = getenv("HOME");
if (!home) return;
char filepath[1024];
snprintf(filepath, sizeof(filepath), "%s/.myshell_bookmarks", home);
FILE* f = fopen(filepath, "w");
if (!f) return;
for (int i = 0; i < bookmark_count; i++) {
fprintf(f, "%s:%s\n", bookmarks[i].name, bookmarks[i].path);
}
fclose(f);
}
// Add or update a bookmark
void add_bookmark(char* name, char* path) {
// Check if bookmark already exists
for (int i = 0; i < bookmark_count; i++) {
if (strcmp(bookmarks[i].name, name) == 0) {
free(bookmarks[i].path);
bookmarks[i].path = strdup(path);
save_bookmarks();
return;
}
}
// Add new bookmark
if (bookmark_count < MAX_BOOKMARKS) {
bookmarks[bookmark_count].name = strdup(name);
bookmarks[bookmark_count].path = strdup(path);
bookmark_count++;
save_bookmarks();
} else {
fprintf(stderr, "myshell: maximum number of bookmarks reached\n");
}
}
// Get bookmark path
char* get_bookmark(char* name) {
for (int i = 0; i < bookmark_count; i++) {
if (strcmp(bookmarks[i].name, name) == 0) {
return bookmarks[i].path;
}
}
return NULL;
}
// Built-in: mark
int builtin_mark(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: mark: missing bookmark name\n");
fprintf(stderr, "Usage: mark <name>\n");
return 1;
}
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
perror("myshell: getcwd");
return 1;
}
add_bookmark(args[1], cwd);
printf("📌 Bookmarked '%s' -> %s\n", args[1], cwd);
return 1;
}
// Built-in: jump
int builtin_jump(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: jump: missing bookmark name\n");
fprintf(stderr, "Usage: jump <name>\n");
return 1;
}
char* path = get_bookmark(args[1]);
if (path == NULL) {
fprintf(stderr, "myshell: jump: bookmark '%s' not found\n", args[1]);
return 1;
}
if (chdir(path) != 0) {
perror("myshell: jump");
return 1;
}
printf("🚀 Jumped to '%s' (%s)\n", args[1], path);
return 1;
}
// Built-in: marks
int builtin_marks(char** args) {
if (bookmark_count == 0) {
printf("No bookmarks defined.\n");
printf("Use 'mark <name>' to bookmark current directory.\n");
return 1;
}
printf("📚 Directory Bookmarks:\n");
for (int i = 0; i < bookmark_count; i++) {
printf(" %s -> %s\n", bookmarks[i].name, bookmarks[i].path);
}
return 1;
}
// Built-in: unmark
int builtin_unmark(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: unmark: missing bookmark name\n");
fprintf(stderr, "Usage: unmark <name>\n");
return 1;
}
for (int i = 0; i < bookmark_count; i++) {
if (strcmp(bookmarks[i].name, args[1]) == 0) {
printf("🗑️ Removed bookmark '%s'\n", args[1]);
// Free memory
free(bookmarks[i].name);
free(bookmarks[i].path);
// Shift remaining bookmarks
for (int j = i; j < bookmark_count - 1; j++) {
bookmarks[j] = bookmarks[j + 1];
}
bookmark_count--;
save_bookmarks();
return 1;
}
}
fprintf(stderr, "myshell: unmark: bookmark '%s' not found\n", args[1]);
return 1;
}
// Session Notes Functions
// Save a note
void save_note(char* note) {
char* home = getenv("HOME");
if (!home) return;
char filepath[1024];
snprintf(filepath, sizeof(filepath), "%s/.myshell_notes", home);
FILE* f = fopen(filepath, "a");
if (!f) return;
// Get current timestamp
time_t now = time(NULL);
struct tm* t = localtime(&now);
char timestamp[64];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", t);
fprintf(f, "[%s] %s\n", timestamp, note);
fclose(f);
}
// Display all notes
void display_notes() {
char* home = getenv("HOME");
if (!home) return;
char filepath[1024];
snprintf(filepath, sizeof(filepath), "%s/.myshell_notes", home);
FILE* f = fopen(filepath, "r");
if (!f) {
printf("📝 No notes found.\n");
printf("Use 'note <text>' to add a note.\n");
return;
}
printf("📝 Session Notes:\n");
printf("────────────────────────────────────────\n");
char line[MAX_INPUT];
int count = 0;
while (fgets(line, sizeof(line), f)) {
printf("%3d. %s", ++count, line);
}
fclose(f);
if (count == 0) {
printf("No notes found.\n");
}
printf("────────────────────────────────────────\n");
printf("Total: %d note(s)\n", count);
printf("Use 'delnote <n>' to delete a note or 'clearnotes' to delete all.\n");
}
// Built-in: note
int builtin_note(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: note: missing note text\n");
fprintf(stderr, "Usage: note <text>\n");
return 1;
}
// Reconstruct the full note text
char note[MAX_INPUT] = "";
for (int i = 1; args[i] != NULL; i++) {
if (i > 1) strcat(note, " ");
strcat(note, args[i]);
}
save_note(note);
printf("✅ Note saved: %s\n", note);
return 1;
}
// Built-in: notes
int builtin_notes(char** args) {
display_notes();
return 1;
}
// Built-in: clearnotes
int builtin_clearnotes(char** args) {
char* home = getenv("HOME");
if (!home) return 1;
char filepath[1024];
snprintf(filepath, sizeof(filepath), "%s/.myshell_notes", home);
// Ask for confirmation
printf("⚠️ Are you sure you want to delete ALL notes? (y/n): ");
fflush(stdout);
char response[10];
if (fgets(response, sizeof(response), stdin)) {
if (response[0] == 'y' || response[0] == 'Y') {
if (remove(filepath) == 0) {
printf("✅ All notes cleared!\n");
} else {
printf("📝 No notes to clear.\n");
}
} else {
printf("❌ Cancelled.\n");
}
}
return 1;
}
// Built-in: delnote
int builtin_delnote(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: delnote: missing note number\n");
fprintf(stderr, "Usage: delnote <n>\n");
return 1;
}
int note_num = atoi(args[1]);
if (note_num <= 0) {
fprintf(stderr, "myshell: delnote: invalid note number\n");
return 1;
}
char* home = getenv("HOME");
if (!home) return 1;
char filepath[1024];
snprintf(filepath, sizeof(filepath), "%s/.myshell_notes", home);
FILE* f = fopen(filepath, "r");
if (!f) {
printf("📝 No notes found.\n");
return 1;
}
// Read all notes into memory
char notes[MAX_NOTES][MAX_INPUT];
int count = 0;
while (fgets(notes[count], MAX_INPUT, f) && count < MAX_NOTES) {
count++;
}
fclose(f);
if (note_num > count) {
fprintf(stderr, "myshell: delnote: note number %d not found (total: %d)\n", note_num, count);
return 1;
}
// Rewrite file without the deleted note
f = fopen(filepath, "w");
if (!f) {
perror("myshell: delnote");
return 1;
}
for (int i = 0; i < count; i++) {
if (i != note_num - 1) { // Skip the note to delete (convert to 0-based index)
fprintf(f, "%s", notes[i]);
}
}
fclose(f);
printf("✅ Deleted note #%d\n", note_num);
return 1;
}
// Built-in: exec
int builtin_exec(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: exec: missing command\n");
fprintf(stderr, "Usage: exec <command> [args...]\n");
return 1;
}
// Save history before exec
save_history_to_file();
// Expand aliases
char* expanded = expand_aliases(args[1]);
// Execute the command, replacing the shell process
execvp(args[1], &args[1]);
// If we get here, exec failed
perror("myshell: exec");
return 1;
}
// Built-in: source
int builtin_source(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: source: missing filename\n");
fprintf(stderr, "Usage: source <file>\n");
return 1;
}
FILE* f = fopen(args[1], "r");
if (!f) {
perror("myshell: source");
return 1;
}
printf("Sourcing %s...\n", args[1]);
char line[MAX_INPUT];
int line_num = 0;
int errors = 0;
while (fgets(line, sizeof(line), f)) {
line_num++;
// Remove newline
line[strcspn(line, "\n")] = 0;
// Skip empty lines and comments
char* trimmed = line;
while (*trimmed == ' ' || *trimmed == '\t') trimmed++;
if (*trimmed == '\0' || *trimmed == '#') continue;
// Expand aliases
char* expanded = expand_aliases(trimmed);
// Check if it's an arithmetic expression
if (is_arithmetic_expression(expanded)) {
double result = evaluate_expression(expanded);
if (result == (int)result) {
printf("%d\n", (int)result);
} else {
printf("%.2f\n", result);
}
} else {
// Parse and execute command
char** cmd_args = parse_input(strdup(expanded));
if (cmd_args[0] != NULL) {
// Execute command silently unless it's echo or similar
int status = execute_command(cmd_args);
if (status == 0) {
fprintf(stderr, "myshell: source: line %d: command failed\n", line_num);
errors++;
}
}
free(cmd_args);
}
}
fclose(f);
if (errors > 0) {
printf("⚠️ Sourced %s with %d error(s)\n", args[1], errors);
} else {
printf("✅ Successfully sourced %s\n", args[1]);
}
return 1;
}
// Built-in: type
int builtin_type(char** args) {
if (args[1] == NULL) {
fprintf(stderr, "myshell: type: missing argument\n");
fprintf(stderr, "Usage: type <command>\n");
return 1;
}
char* cmd = args[1];
// Check if it's a builtin
for (int i = 0; i < num_builtins(); i++) {
if (strcmp(cmd, builtin_names[i]) == 0) {
printf("%s is a shell builtin\n", cmd);
return 1;
}
}
// Check if it's an alias
char* alias_value = get_alias(cmd);
if (alias_value) {
printf("%s is aliased to `%s'\n", cmd, alias_value);
return 1;
}
// Search in PATH
char* path_env = getenv("PATH");
if (!path_env) {
printf("%s: not found\n", cmd);
return 1;
}
char* path = strdup(path_env);
char* dir = strtok(path, ":");
int found = 0;
while (dir) {
char full_path[2048];
snprintf(full_path, sizeof(full_path), "%s/%s", dir, cmd);
if (access(full_path, X_OK) == 0) {
printf("%s is %s\n", cmd, full_path);
found = 1;
break;
}
dir = strtok(NULL, ":");
}
free(path);
if (!found) {
printf("%s: not found\n", cmd);
}
return 1;
}
// Check if string is an arithmetic expression
int is_arithmetic_expression(char* str) {
if (str == NULL || strlen(str) == 0) return 0;
int has_digit = 0;
int has_operator = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i]) || str[i] == '.') {
has_digit = 1;
} else if (str[i] == '+' || str[i] == '-' || str[i] == '*' ||
str[i] == '/' || str[i] == '%' || str[i] == '(' ||
str[i] == ')' || str[i] == ' ' || str[i] == '^') {
if (str[i] != ' ' && str[i] != '(' && str[i] != ')') {
has_operator = 1;
}
} else {
return 0; // Invalid character for arithmetic
}
}
return has_digit && has_operator;
}
// Simple expression parser
double parse_number(char** expr) {
double result = 0;
double decimal = 0;
int decimal_places = 0;
while (isdigit(**expr) || **expr == '.') {
if (**expr == '.') {
decimal_places = 1;
} else if (decimal_places > 0) {
decimal = decimal * 10 + (**expr - '0');
decimal_places++;
} else {
result = result * 10 + (**expr - '0');
}
(*expr)++;
}
if (decimal_places > 1) {
for (int i = 1; i < decimal_places; i++) {
decimal /= 10.0;
}
result += decimal;
}
return result;
}
double parse_factor(char** expr);
double parse_term(char** expr);
double parse_expr(char** expr);
double parse_factor(char** expr) {
while (**expr == ' ') (*expr)++;
if (**expr == '(') {
(*expr)++;
double result = parse_expr(expr);
if (**expr == ')') (*expr)++;
return result;
}
if (**expr == '-') {
(*expr)++;
return -parse_factor(expr);
}
if (**expr == '+') {
(*expr)++;
return parse_factor(expr);
}
return parse_number(expr);
}
double parse_power(char** expr) {
double result = parse_factor(expr);
while (**expr == ' ') (*expr)++;
if (**expr == '^') {
(*expr)++;
double exponent = parse_power(expr);
double base = result;
result = 1;
for (int i = 0; i < (int)exponent; i++) {
result *= base;
}
}
return result;
}
double parse_term(char** expr) {
double result = parse_power(expr);
while (1) {
while (**expr == ' ') (*expr)++;
if (**expr == '*') {
(*expr)++;
result *= parse_power(expr);
} else if (**expr == '/') {
(*expr)++;
double divisor = parse_power(expr);
if (divisor != 0) {
result /= divisor;