xref: /freebsd/bin/sh/cd.c (revision df7f5d4de4592a8948a25ce01e5bddfbb7ce39dc)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	$Id$
37  */
38 
39 #ifndef lint
40 static char const sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
41 #endif /* not lint */
42 
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <errno.h>
49 
50 /*
51  * The cd and pwd commands.
52  */
53 
54 #include "shell.h"
55 #include "var.h"
56 #include "nodes.h"	/* for jobs.h */
57 #include "jobs.h"
58 #include "options.h"
59 #include "output.h"
60 #include "memalloc.h"
61 #include "error.h"
62 #include "exec.h"
63 #include "redir.h"
64 #include "mystring.h"
65 #include "show.h"
66 #include "cd.h"
67 
68 STATIC int docd __P((char *, int));
69 STATIC char *getcomponent __P((void));
70 STATIC void updatepwd __P((char *));
71 
72 char *curdir = NULL;		/* current working directory */
73 char *prevdir;			/* previous working directory */
74 STATIC char *cdcomppath;
75 
76 int
77 cdcmd(argc, argv)
78 	int argc;
79 	char **argv;
80 {
81 	char *dest;
82 	char *path;
83 	char *p;
84 	struct stat statb;
85 	int print = 0;
86 
87 	nextopt(nullstr);
88 	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
89 		error("HOME not set");
90 	if (*dest == '\0')
91 		dest = ".";
92 	if (dest[0] == '-' && dest[1] == '\0') {
93 		dest = prevdir ? prevdir : curdir;
94 		if (dest)
95 			print = 1;
96 		else
97 			dest = ".";
98 	}
99 	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
100 		path = nullstr;
101 	while ((p = padvance(&path, dest)) != NULL) {
102 		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
103 			if (!print) {
104 				/*
105 				 * XXX - rethink
106 				 */
107 				if (p[0] == '.' && p[1] == '/')
108 					p += 2;
109 				print = strcmp(p, dest);
110 			}
111 			if (docd(p, print) >= 0)
112 				return 0;
113 
114 		}
115 	}
116 	error("can't cd to %s", dest);
117 	/*NOTREACHED*/
118 	return 0;
119 }
120 
121 
122 /*
123  * Actually do the chdir.  In an interactive shell, print the
124  * directory name if "print" is nonzero.
125  */
126 STATIC int
127 docd(dest, print)
128 	char *dest;
129 	int print;
130 {
131 
132 	TRACE(("docd(\"%s\", %d) called\n", dest, print));
133 	INTOFF;
134 	updatepwd(dest);
135 	if (chdir(stackblock()) < 0) {
136 		INTON;
137 		return -1;
138 	}
139 	hashcd();				/* update command hash table */
140 	if (prevdir)
141 		ckfree(prevdir);
142 	prevdir = curdir;
143 	curdir = savestr(stackblock());
144 	INTON;
145 	if (print && iflag)
146 		out1fmt("%s\n", stackblock());
147 	return 0;
148 }
149 
150 
151 /*
152  * Get the next component of the path name pointed to by cdcomppath.
153  * This routine overwrites the string pointed to by cdcomppath.
154  */
155 STATIC char *
156 getcomponent()
157 {
158 	register char *p;
159 	char *start;
160 
161 	if ((p = cdcomppath) == NULL)
162 		return NULL;
163 	start = cdcomppath;
164 	while (*p != '/' && *p != '\0')
165 		p++;
166 	if (*p == '\0') {
167 		cdcomppath = NULL;
168 	} else {
169 		*p++ = '\0';
170 		cdcomppath = p;
171 	}
172 	return start;
173 }
174 
175 
176 /*
177  * Determine the new working directory, but don't actually enforce
178  * any changes.
179  */
180 STATIC void
181 updatepwd(dir)
182 	char *dir;
183 {
184 	char *new;
185 	char *p;
186 
187 	cdcomppath = stalloc(strlen(dir) + 1);
188 	scopy(dir, cdcomppath);
189 	STARTSTACKSTR(new);
190 	if (*dir != '/') {
191 		if (curdir == NULL)
192 			return;
193 		p = curdir;
194 		while (*p)
195 			STPUTC(*p++, new);
196 		if (p[-1] == '/')
197 			STUNPUTC(new);
198 	}
199 	while ((p = getcomponent()) != NULL) {
200 		if (equal(p, "..")) {
201 			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
202 		} else if (*p != '\0' && ! equal(p, ".")) {
203 			STPUTC('/', new);
204 			while (*p)
205 				STPUTC(*p++, new);
206 		}
207 	}
208 	if (new == stackblock())
209 		STPUTC('/', new);
210 	STACKSTRNUL(new);
211 }
212 
213 
214 int
215 pwdcmd(argc, argv)
216 	int argc;
217 	char **argv;
218 {
219 	if (!getpwd())
220 		error("getcwd() failed: %s", strerror(errno));
221 	out1str(curdir);
222 	out1c('\n');
223 	return 0;
224 }
225 
226 
227 /*
228  * Find out what the current directory is. If we already know the current
229  * directory, this routine returns immediately.
230  */
231 char *
232 getpwd()
233 {
234 	if (curdir)
235 		return (curdir);
236 	return ((curdir = getcwd(NULL, 0)));
237 }
238