Search code examples
shellunix

What happens if I invoke shell with directory as first argument?


What exactly happens when I call dash with existing directory as first argument? For example,

% mkdir -p tmp_dir
% dash tmp_dir

And it exits with code 0.

If I replace dash with bash or zsh, execution fails (and it is was I expected with dash)

% bash tmp_dir
tmp_dir: tmp_dir: is a directory

From the man page, dash expects path to script file as its first argument and I known, that in UNIX everything is a file (even if is a directory). But what exactly happens and why dash has such (surprising) behavoir?


Solution

  • What exactly happens

    $ strace dash tmp_dir  2>&1 | grep -E 'open|read'
    ...
    openat(AT_FDCWD, "tmp_dir", O_RDONLY)      = 3
    read(10, 0x561bef5bacc0, 8192)          = -1 EISDIR (Is a directory)
    

    dash process open() s the tmp_dir and receives a file descriptor. Then it tries to read() from the file descriptor and receifves EISDIR error.

    From https://github.com/danishprakash/dash/blob/a9481f4a453f0ad25d9c9068c7b6e47253532deb/dash.c#L580 dash just calls getchar() and stops reading upon receiving EOF.

    getchar return EOF both on error and on end of file. dash doesn't differentiate between these conditions and does not check errno for errors and just exits as-if an empty file was read.