[hackers] [PATCH] Implement -p for xargs(1)

From: =?UTF-8?q?Pekka=20Jylh=C3=A4-Ollila?= <pekka.jylha.ollila_AT_gmail.com>
Date: Tue, 16 Feb 2016 07:42:53 +0200

This patch implements prompting for user input before executing
commands. Input is read from /dev/tty as per posix 2013 spec.
---
 README  |  2 +-
 xargs.1 |  6 +++++-
 xargs.c | 28 +++++++++++++++++++++++++---
 3 files changed, 31 insertions(+), 5 deletions(-)
diff --git a/README b/README
index 68a921c..e8b16b0 100644
--- a/README
+++ b/README
_AT_@ -99,7 +99,7 @@ The following tools are implemented:
 #*|o wc          .
 =*|x which       .
 =*|x whoami      .
-=*|o xargs       (-p)
+=*|o xargs       .
 =*|x yes         .
 
 The  complement of  sbase  is  ubase[1] which  is  Linux-specific  and
diff --git a/xargs.1 b/xargs.1
index 47cc194..1015756 100644
--- a/xargs.1
+++ b/xargs.1
_AT_@ -6,7 +6,7 @@
 .Nd construct argument lists and execute command
 .Sh SYNOPSIS
 .Nm
-.Op Fl rtx
+.Op Fl prtx
 .Op Fl E Ar eofstr
 .Op Fl n Ar num
 .Op Fl s Ar num
_AT_@ -36,6 +36,10 @@ newlines, may be escaped by a backslash.
 Use at most
 .Ar num
 arguments per command line.
+.It Fl p
+Prompt before running each command. Run the command only if the response
+starts with 'y' or 'Y'. Implies
+.Fl t .
 .It Fl r
 Do not run the command if there are no arguments. Normally the command is
 executed at least once even if there are no arguments.
diff --git a/xargs.c b/xargs.c
index 0d5dd53..5b3d214 100644
--- a/xargs.c
+++ b/xargs.c
_AT_@ -26,7 +26,7 @@ static size_t argbsz;
 static size_t argbpos;
 static size_t maxargs = 0;
 static int    nerrors = 0;
-static int    rflag = 0, nflag = 0, tflag = 0, xflag = 0;
+static int    nflag = 0, pflag = 0, rflag = 0, tflag = 0, xflag = 0;
 static char  *argb;
 static char  *cmd[NARGS];
 static char  *eofstr;
_AT_@ -162,15 +162,34 @@ spawn(void)
 	int savederrno;
 	int first = 1;
 	char **p;
+	FILE *tty;
+	int ch, savedch;
 
-	if (tflag) {
+	if (pflag || tflag) {
 		for (p = cmd; *p; p++) {
 			if (!first)
 				fputc(' ', stderr);
 			fputs(*p, stderr);
 			first = 0;
 		}
+	}
+
+	if (!pflag && tflag)
 		fputc('\n', stderr);
+
+	if (pflag) {
+		fputs(" ?...", stderr);
+
+		tty = fopen("/dev/tty", "r");
+		if (!tty)
+			return;
+		ch = savedch = fgetc(tty);
+		while (ch != EOF && ch != '\n')
+			ch = getc(tty);
+		fclose(tty);
+
+		if (savedch != 'y' && savedch != 'Y')
+			return;
 	}
 
 	switch (fork()) {
_AT_@ -188,7 +207,7 @@ spawn(void)
 static void
 usage(void)
 {
-	eprintf("usage: %s [-rtx] [-E eofstr] [-n num] [-s num] "
+	eprintf("usage: %s [-prtx] [-E eofstr] [-n num] [-s num] "
 	        "[cmd [arg ...]]\n", argv0);
 }
 
_AT_@ -210,6 +229,9 @@ main(int argc, char *argv[])
 		nflag = 1;
 		maxargs = estrtonum(EARGF(usage()), 1, MIN(SIZE_MAX, LLONG_MAX));
 		break;
+	case 'p':
+		pflag = 1;
+		break;
 	case 'r':
 		rflag = 1;
 		break;
-- 
2.1.4
Received on Tue Feb 16 2016 - 06:42:53 CET

This archive was generated by hypermail 2.3.0 : Tue Feb 16 2016 - 06:48:21 CET