[PATCH v2] cmd: cat: add new command

Roger Knecht rknecht at pm.me
Sat Jun 4 13:19:15 CEST 2022


Add cat command to print file content to standard out

Signed-off-by: Roger Knecht <rknecht at pm.me>
---
v2:
 - Moved cat from boot to shell commands
 - Added MAINTAINERS entry
 - Added comments
 - Improved variable naming

 MAINTAINERS  |  5 +++++
 cmd/Kconfig  |  6 ++++++
 cmd/Makefile |  1 +
 cmd/cat.c    | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 70 insertions(+)
 create mode 100644 cmd/cat.c

diff --git a/MAINTAINERS b/MAINTAINERS
index 56be0bfad0..7c5cd178d9 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -729,6 +729,11 @@ M:	Simon Glass <sjg at chromium.org>
 S:	Maintained
 F:	tools/buildman/

+CAT
+M:	Roger Knecht <rknecht at pm.me>
+S:	Maintained
+F:	cmd/cat.c
+
 CFI FLASH
 M:	Stefan Roese <sr at denx.de>
 S:	Maintained
diff --git a/cmd/Kconfig b/cmd/Kconfig
index 69c1814d24..8b531c7ebe 100644
--- a/cmd/Kconfig
+++ b/cmd/Kconfig
@@ -1492,6 +1492,12 @@ endmenu

 menu "Shell scripting commands"

+config CMD_CAT
+	bool "cat"
+	default y
+	help
+	  Print file to standard output
+
 config CMD_ECHO
 	bool "echo"
 	default y
diff --git a/cmd/Makefile b/cmd/Makefile
index 5e43a1e022..589b9680ba 100644
--- a/cmd/Makefile
+++ b/cmd/Makefile
@@ -38,6 +38,7 @@ obj-$(CONFIG_CMD_BOOTZ) += bootz.o
 obj-$(CONFIG_CMD_BOOTI) += booti.o
 obj-$(CONFIG_CMD_BTRFS) += btrfs.o
 obj-$(CONFIG_CMD_BUTTON) += button.o
+obj-$(CONFIG_CMD_CAT) += cat.o
 obj-$(CONFIG_CMD_CACHE) += cache.o
 obj-$(CONFIG_CMD_CBFS) += cbfs.o
 obj-$(CONFIG_CMD_CLK) += clk.o
diff --git a/cmd/cat.c b/cmd/cat.c
new file mode 100644
index 0000000000..a027d842ef
--- /dev/null
+++ b/cmd/cat.c
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright 2022
+ * Roger Knecht <rknecht at pm.de>
+ */
+
+#include <common.h>
+#include <command.h>
+#include <fs.h>
+#include <malloc.h>
+
+static int do_cat(struct cmd_tbl *cmdtp, int flag, int argc,
+		  char *const argv[])
+{
+	char *file_data;
+	loff_t file_index;
+	loff_t file_size;
+	int ret;
+
+	if (argc < 4)
+		return CMD_RET_USAGE;
+
+	ret = fs_set_blk_dev(argv[1], argv[2], FS_TYPE_ANY);
+	if (ret)
+		return ret;
+
+	// get file size
+	ret = fs_size(argv[3], &file_size);
+	if (ret)
+		return ret;
+
+	// allocate memory for file content
+	file_data = malloc(file_size);
+	if (!file_data)
+		return -ENOMEM;
+
+	ret = fs_set_blk_dev(argv[1], argv[2], FS_TYPE_ANY);
+	if (ret)
+		return ret;
+
+	// read file to memory
+	ret = fs_read(argv[3], (ulong)file_data, 0, 0, &file_size);
+	if (ret)
+		return ret;
+
+	// print file content
+	for (file_index = 0; file_index < file_size; file_index++)
+		putc(file_data[file_index]);
+
+	free(file_data);
+
+	return 0;
+}
+
+U_BOOT_CMD(cat, 4, 1, do_cat,
+	   "print file to standard output",
+	   "<interface> <dev[:part]> <file>\n"
+	   "	- Print file from 'dev' on 'interface' to standard output");
--
2.17.1




More information about the U-Boot mailing list