r/C_Programming • • Jun 18 '26

Shell in C

I built a small UNIX shell in C as a learning project and just released v0.0.1

Features so far:

  • External command execution
  • cd
  • cd ~
  • exit

GitHub: https://github.com/Dhananjay-Jha-1/dsh

I'd highly appreciate feedback on the code structure or anything related to code in general.
The shell is really primitive at this stage and I want to take it forward.

6 Upvotes

20 comments sorted by

View all comments

Show parent comment

2

u/flyingron Jun 22 '26

Actually, other than being one large file, it doesn't look too bad. I'd have put the builtin and their implementing function in a struct so that the name and function get maintained together (otherwise you have to modify two arrays each time you add one and have to make sure you keep them in the same order).

Here's sort of a rough way to break them up...

Divide up the source into logical segments. You might put all the builtins in one file, for instance, the execution in another, etc... Then you'll need to find which functions (and other things) that are shared between files and move declarations of those to an include file,

Then you compile each .c file into .o files and then link the .o files together into the executiable. Make has some default rules to make this easy anyhow

Let's say you have tsh.c for your program main loop, and you put the builtins into builtin.c with their declarations in builtin.h (which you then #include into main), then your make will look something like:

tsh:   tsh.o builtin.o
  cc $^ -o $@

tsh.o:  tsh.c builtin.h

builtin.o:   builtin.c builtin.h

The first line just says to build tsh, you need tsh.o and builtin.o. The $^ evaluates to the dependencies (tsh.o and builtion.o) so you don't have to retype them. $@ evaluates to the target (tsh).

Since this is the first in the makefile, it is the one executed by default if you just say "make." Of course, you could build one of the others by saying "make tsh.o" or whatever.

The other two lines indicate that tsh.o depends on tsh.c and builtin.h, if either of them changes then tsh.o needs to be recompiled. Similar for builtin.o. You could put the command "cc -c $<" to indicate the command but Make has default rules to make .o from .c files,s o you don't need to do it explicitly.

The first time you type make, it will build tsh.o and then builtin.o and then combine those to make tsh. After that, if you changed builtin.c only, it will be smart enough to realize that it doesn't have to rebuild tsh.o and just builds builtin.o and then tsh.

CMake doesn't actually build anything. It is a programming language that allows you to write portable build scripts that it compiles into Makefiles or Visual Studio project files or whatever you want...

Hope that helps.

1

u/Imaginary-Dig-7835 Jun 23 '26

Thanks a lot dude. It really helped. ✌🏻