~emersion/mrsh

ref: 1af38099508a577e3e312693048bf1148c9ad768 mrsh/builtin/pwd.c -rw-r--r-- 949 bytes View raw
                                                                                
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
#define _POSIX_C_SOURCE 200809L
#include <mrsh/getopt.h>
#include <mrsh/shell.h>
#include <stdio.h>
#include <stdlib.h>
#include "builtin.h"

static const char pwd_usage[] = "usage: pwd [-L|-P]\n";

int builtin_pwd(struct mrsh_state *state, int argc, char *argv[]) {
	mrsh_optind = 1;
	int opt;
	while ((opt = mrsh_getopt(argc, argv, ":LP")) != -1) {
		switch (opt) {
		case 'L':
		case 'P':
			// TODO implement `-L` and `-P`
			fprintf(stderr, "pwd: `-L` and `-P` not yet implemented\n");
			return EXIT_FAILURE;
		default:
			fprintf(stderr, "pwd: unknown option -- %c\n", mrsh_optopt);
			fprintf(stderr, pwd_usage);
			return EXIT_FAILURE;
		}
	}
	if (mrsh_optind < argc) {
		fprintf(stderr, pwd_usage);
		return EXIT_FAILURE;
	}

	const char *pwd = mrsh_env_get(state, "PWD", NULL);
	if (pwd == NULL) {
		fprintf(stderr, "pwd: Cannot return current directory as PWD was unset\n");
		return EXIT_FAILURE;
	}
	puts(pwd);
	return EXIT_SUCCESS;
}