[PATCH] main: don't raise exception when executing dotcmd() on a non-existent file

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



When sourcing a file with the dotcmd() builtin, dash raises an exception
when the input file cannot be opened.

For instance the following script fails prematurely and does not output
the message:

  #!/bin/sh

  . /non-existent-file
  echo "Survived!"

In this case, the behavior of dash is different from other shells (e.g.
bash, zsh) which are more forgiving and allow execution to carry on even
if the input file cannot be opened.

Fix this by passing the INPUT_NOFILE_OK flag when calling setinputfile()
in dotcmd().

As a bonus, this also fixes cases like the following:

  set -e
  . /non-existent-file || true
  echo "Survived! Let's do something else..."

This idiom is sometimes used in shell script to source a config file
with default values only to provide fallback values if the default
values were not available.

Signed-off-by: Antonio Ospite <ao2@xxxxxx>
---

Hi Herbert,

I also thought about printing the warning in setinputfile() itself, maybe
guarding the printout with a new flag, like INPUT_NOFILE_OK_SILENT, which
could be used by readprofile() to keep the current silent behavior when
profile files are not found.

I though i'd send this simple version first to see if changing the behavior of
dotcmd() is acceptable in the first place. If it is we can then discuss about
how to do it.

Thank you,
   Antonio

 src/main.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/src/main.c b/src/main.c
index 6d53e00..a229d68 100644
--- a/src/main.c
+++ b/src/main.c
@@ -331,12 +331,18 @@ dotcmd(int argc, char **argv)
 		char *fullname;
 
 		fullname = find_dot_file(*argv);
-		setinputfile(fullname, INPUT_PUSH_FILE);
+		status = setinputfile(fullname, INPUT_PUSH_FILE | INPUT_NOFILE_OK);
+		if (status < 0) {
+			sh_warnx("%s: %s", fullname, strerror(errno));
+			status = 1;
+			goto out;
+		}
 		commandname = fullname;
 		status = cmdloop(0);
 		popfile();
 	}
 
+out:
 	return status;
 }
 
-- 
2.19.2




[Index of Archives]     [LARTC]     [Bugtraq]     [Yosemite Forum]     [Photo]

  Powered by Linux