summaryrefslogtreecommitdiffstats
path: root/commands/readf.c
diff options
context:
space:
mode:
authorSascha Hauer <s.hauer@pengutronix.de>2014-02-13 19:32:30 +0100
committerSascha Hauer <s.hauer@pengutronix.de>2014-02-14 16:40:13 +0100
commit3b7a102d3e64ed2d6b43d8e19d94568d695931a3 (patch)
tree54fa141901fb062d1de0c4db8d84cc336d286907 /commands/readf.c
parent6280e991eef453aba8ed1187db60992fad785d7d (diff)
downloadbarebox-3b7a102d3e64ed2d6b43d8e19d94568d695931a3.tar.gz
barebox-3b7a102d3e64ed2d6b43d8e19d94568d695931a3.tar.xz
Add readf command
The readf command is useful to read the content of a file into a shell variable. It should be used for ascii content and thus stops reading at all nonprintable characters including newline. Signed-off-by: Sascha Hauer <s.hauer@pengutronix.de>
Diffstat (limited to 'commands/readf.c')
-rw-r--r--commands/readf.c63
1 files changed, 63 insertions, 0 deletions
diff --git a/commands/readf.c b/commands/readf.c
new file mode 100644
index 000000000..6314c7ef2
--- /dev/null
+++ b/commands/readf.c
@@ -0,0 +1,63 @@
+#include <common.h>
+#include <command.h>
+#include <fs.h>
+#include <malloc.h>
+#include <linux/stat.h>
+#include <linux/ctype.h>
+#include <environment.h>
+
+static int do_readf(int argc, char *argv[])
+{
+ unsigned char *buf = NULL, *val;
+ char *variable, *filename;
+ struct stat s;
+ size_t size;
+ int ret, i;
+
+ if (argc != 3)
+ return COMMAND_ERROR_USAGE;
+
+ filename = argv[1];
+ variable = argv[2];
+
+ ret = stat(filename, &s);
+ if (ret)
+ goto out;
+
+ if (s.st_size > 1024) {
+ ret = -EFBIG;
+ goto out;
+ }
+
+ buf = read_file(filename, &size);
+ if (!buf)
+ goto out;
+
+ for (i = 0; i < size; i++) {
+ if (!isprint(buf[i])) {
+ buf[i] = '\0';
+ break;
+ }
+ }
+
+ val = strim(buf);
+
+ ret = setenv(variable, val);
+out:
+ free(buf);
+
+ return ret;
+}
+
+BAREBOX_CMD_HELP_START(readf)
+BAREBOX_CMD_HELP_USAGE("readf <file> <variable>\n")
+BAREBOX_CMD_HELP_SHORT("Read a single line of a file into a shell variable. Leading and trailing whitespaces\n")
+BAREBOX_CMD_HELP_SHORT("are removed, nonvisible characters are stripped. Input is limited to 1024\n")
+BAREBOX_CMD_HELP_SHORT("characters.\n")
+BAREBOX_CMD_HELP_END
+
+BAREBOX_CMD_START(readf)
+ .cmd = do_readf,
+ .usage = "read file into variable",
+ BAREBOX_CMD_HELP(cmd_readf_help)
+BAREBOX_CMD_END