How to implement your own cd command in your own shell

I am working on a mini project: "MY OWN COMMAND INTERPRETER (SHELL)" like a Bash shell or Sh shell. Until now, it can execute all predefined commands like ls, ps, pwd, date. In addition, I have implemented some other operations, such as the Input Redirection (<), Output Redirection (>), PIPE (|). Along with this, I have implemented my own custom commands like pid, ppid, quit, hist.

vvdnlt208@vvdnlt208-Vostro-3446:~/project/Vector/sourabh/unix/proj2$ ./my_sh  
<1 SOURABH> ls
 a     cd.c       execute.o  inredir.c  main.o   multiexec.o  my_sh   sh.c                sigign.c  test.c
addhist.c  dir        header.h   inredir.o  Makefile     mypipe.c     outredir.c  showhist.c  sigign.o  tetest.c
addhist.o  execute.c  inredir    main.c     multiexec.c  mypipe.o     outredir.o    showhist.o  test2.c
<2 SOURABH> ps
PID TTY          TIME CMD
6120 pts/10   00:00:01 bash
6510 pts/10   00:00:00 grep
6512 pts/10   00:00:00 grep
6514 pts/10   00:00:00 grep
6516 pts/10   00:00:00 grep
7772 pts/10   00:00:00 my_sh
7774 pts/10   00:00:00 ps
<3 SOURABH> pwd
/home/vvdnlt208/project/Vector/sourabh/unix/proj2
<4 SOURABH> date
Fri Nov 14 16:44:24 IST 2014
<5 SOURABH> 
<6 SOURABH> 
<7 SOURABH> 
<8 SOURABH> hist
1 ls
2 ps
3 pwd
4 date
8 hist
<9 SOURABH> ls >a.txt
<10 SOURABH> pid
7772
<11 SOURABH> ppid

      

But I find it difficult to execute the command cd ...

<12 SOURABH> cd
cd: No such file or directory
<13 SOURABH> cd dir
cd: No such file or directory
<14 SOURABH> 

      

Someone told me to implement it myself ... Please help me on this. Thanks in advance.

+3


source to share


3 answers


cd

not a program, it is a built-in command. The builtin command is directly built into the shell.

To implement cd

you basically need



  • Use chdir()

    to change the current directory
  • Update some environment variables (like Klas Lindback said: OLDPWD

    and PWD

    )
+5


source


You can see the function chdir

in unistd.h

. This changes the working directory of the current process.



+4


source


In my project I have used chdir () to implement my cd command and it works. Each process has its own PWD (real working directory). The shell is also a process, and the default PWD is the PWD of its parent (bash shell where I ran. / My_sh).

0


source







All Articles