From adf20212102fc0d307450f90f4795323b3c6f53d Mon Sep 17 00:00:00 2001 From: Leah Lundqvist Date: Tue, 17 Nov 2026 14:18:05 +0100 Subject: [PATCH] Give a script found through PATH its path as $0 When a shell script was found by a PATH search, gash set $0 to the bare name as typed (`probe`), so `dirname "$0"` was `.`. bash, dash and zsh execve() the path they found, which becomes $0. The npm/pnpm/yarn shims in node_modules/.bin locate their package with `dirname "$0"`, so with gash as npm's script-shell they resolved targets from the current directory instead (pnpm i failing with "Cannot find module"). A PATH hit now records the PATH entry joined with the name of the file found (`./node_modules/.bin/probe`, or the absolute entry as given), and that becomes $0 and BASH_SOURCE for scripts run in-process and the script argument when a separate gash is started. Names typed with a slash and `bash script.sh` are unchanged. Hits in relative PATH entries are no longer hashed, since they depend on the current directory. Co-Authored-By: Claude Opus 5.5 --- src/exec.rs | 50 ++++++++++++++++------ src/shell.rs | 4 ++ tests/scripts/075_path_lookup_dollar0.code | 1 + tests/scripts/075_path_lookup_dollar0.out | 45 +++++++++++++++++++ tests/scripts/075_path_lookup_dollar0.sh | 41 ++++++++++++++++++ 5 files changed, 127 insertions(+), 14 deletions(-) create mode 100644 tests/scripts/075_path_lookup_dollar0.code create mode 100644 tests/scripts/075_path_lookup_dollar0.out create mode 100644 tests/scripts/075_path_lookup_dollar0.sh diff --git a/src/exec.rs b/src/exec.rs index cfcbd63..3db26b5 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -1373,7 +1373,10 @@ impl Shell { } let r = self.find_in_path(name, &p); if let Some(r) = &r { - if self.o[O_HASHALL] { + // A hit in a relative PATH entry (`./node_modules/.bin`) depends on the current + // directory, so it isn't remembered. + let relative = r.found_as.as_deref().is_some_and(|f| !f.starts_with(['/', '\\']) && !path::is_windows_abs(f)); + if self.o[O_HASHALL] && !relative { self.hash.insert(name.to_string(), r.clone()); } } @@ -1388,7 +1391,12 @@ impl Shell { for d in dirs { let d = if d.is_empty() { ".".to_string() } else { d }; let wd = path::to_win(&d, &self.cwd); - if let Some(r) = self.probe(&wd, name, true) { + if let Some(mut r) = self.probe(&wd, name, true) { + // The name of the file actually found (`probe`, or `probe.cmd` for `probe`). + if let Some(f) = r.path.file_name() { + let sep = if d.ends_with(['/', '\\']) { "" } else { "/" }; + r.found_as = Some(format!("{}{}{}", d, sep, f.to_string_lossy())); + } return Some(prefer_native_coreutils(r)); } } @@ -1448,12 +1456,12 @@ impl Shell { match ext.as_str() { "exe" | "com" => { if let Some(util) = crate::coreutils::get().and_then(|cu| cu.util_of(p)) { - return Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Coreutils, interp: None, util: Some(util), opts: Vec::new() }); + return Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Coreutils, interp: None, util: Some(util), opts: Vec::new(), found_as: None }); } let kind = if path::is_msys_binary(p) || is_msys_dir(p) { ExeKind::Msys } else { ExeKind::Native }; - return Some(Resolved { path: p.to_path_buf(), kind, interp: None, util: None, opts: Vec::new() }); + return Some(Resolved { path: p.to_path_buf(), kind, interp: None, util: None, opts: Vec::new(), found_as: None }); } - "bat" | "cmd" => return Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Batch, interp: None, util: None, opts: Vec::new() }), + "bat" | "cmd" => return Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Batch, interp: None, util: None, opts: Vec::new(), found_as: None }), _ => {} } let mut f = std::fs::File::open(p).ok()?; @@ -1462,7 +1470,7 @@ impl Shell { let head = &buf[..n]; if head.starts_with(b"MZ") { let kind = if is_msys_dir(p) { ExeKind::Msys } else { ExeKind::Native }; - return Some(Resolved { path: p.to_path_buf(), kind, interp: None, util: None, opts: Vec::new() }); + return Some(Resolved { path: p.to_path_buf(), kind, interp: None, util: None, opts: Vec::new(), found_as: None }); } if head.starts_with(b"#!") { let line_end = head.iter().position(|&b| b == b'\n').unwrap_or(head.len()); @@ -1486,7 +1494,7 @@ impl Shell { }; let pbase = prog.rsplit(['/', '\\']).next().unwrap_or("").trim_end_matches(".exe").to_string(); if matches!(pbase.as_str(), "sh" | "bash" | "dash" | "ash" | "gash") && arg.as_deref().map(|a| !a.contains("-c")).unwrap_or(true) { - return Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Script, interp: None, util: None, opts }); + return Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Script, interp: None, util: None, opts, found_as: None }); } // locate interpreter let ip = if prog.contains('/') || prog.contains('\\') { @@ -1516,12 +1524,12 @@ impl Shell { }; let ip = ip?; let ik = if path::is_msys_binary(&ip) || is_msys_dir(&ip) { ExeKind::Msys } else { ExeKind::Native }; - return Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Interp, interp: Some((ip, ik, arg)), util: None, opts: Vec::new() }); + return Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Interp, interp: Some((ip, ik, arg)), util: None, opts: Vec::new(), found_as: None }); } if strict && ext != "sh" { return None; } - Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Script, interp: None, util: None, opts: Vec::new() }) + Some(Resolved { path: p.to_path_buf(), kind: ExeKind::Script, interp: None, util: None, opts: Vec::new(), found_as: None }) } // ---------- external commands ---------- @@ -1614,7 +1622,14 @@ impl Shell { for o in &res.opts { cmd.arg(o); } - cmd.arg(res.path.as_os_str()); + // The new shell runs in our directory, so the script's `$0` can be given as is + // (a name starting with `-` would be taken for an option). + let arg0 = script_arg0(res, argv); + if arg0.starts_with('-') { + cmd.arg(res.path.as_os_str()); + } else { + cmd.arg(arg0); + } for a in &argv[1..] { cmd.arg(a); } @@ -1783,12 +1798,13 @@ impl Shell { } }; let mut child = self.child_shell(assigns); - if !res.opts.is_empty() && !apply_shebang_opts(&mut child, &res.opts, &argv[0]) { + let arg0 = script_arg0(res, argv); + if !res.opts.is_empty() && !apply_shebang_opts(&mut child, &res.opts, &arg0) { return None; } - child.arg0 = argv[0].clone(); + child.arg0 = arg0.clone(); child.positional = argv[1..].to_vec(); - child.source_name = argv[0].clone(); + child.source_name = arg0; let st = child.run_main(&src); Some(Ok(st)) } @@ -2060,6 +2076,12 @@ fn names_std_fd(args: &[String], fd: i32) -> bool { }) } +/// `$0` for a shell script about to run: where a PATH search found it, or else the name as +/// typed (which then has a slash in it). Scripts find their own folder with `dirname "$0"`. +fn script_arg0(res: &Resolved, argv: &[String]) -> String { + res.found_as.clone().unwrap_or_else(|| argv[0].clone()) +} + /// Applies the options on a script's `#!` line (`#!/bin/bash -e`, `#!/usr/bin/env -S bash -eu`) /// to the shell that runs it, with bash's command-line syntax. Returns false for anything that /// would make bash print something or refuse to start (an invalid option, `--version`, ...); @@ -2091,7 +2113,7 @@ fn prefer_native_coreutils(r: Resolved) -> Resolved { }; match crate::coreutils::static_name(&stem) { Some(util) if path::is_msys_binary(&r.path) => { - Resolved { path: cu.program(util), kind: ExeKind::Coreutils, interp: None, util: Some(util), opts: Vec::new() } + Resolved { path: cu.program(util), kind: ExeKind::Coreutils, interp: None, util: Some(util), opts: Vec::new(), found_as: None } } _ => r, } diff --git a/src/shell.rs b/src/shell.rs index 7d428f2..68464dc 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -289,6 +289,10 @@ pub struct Resolved { pub util: Option<&'static str>, /// For ExeKind::Script: the options on its `#!` line, as bash would be given them. pub opts: Vec, + /// When found by a PATH search: the PATH entry joined with the name of the file found + /// (`./node_modules/.bin/probe`). A script run this way gets it as `$0`, as a shell that + /// execve()s the path it found does. + pub found_as: Option, } static FAKE_PID: AtomicU32 = AtomicU32::new(0); diff --git a/tests/scripts/075_path_lookup_dollar0.code b/tests/scripts/075_path_lookup_dollar0.code new file mode 100644 index 0000000..c227083 --- /dev/null +++ b/tests/scripts/075_path_lookup_dollar0.code @@ -0,0 +1 @@ +0 \ No newline at end of file diff --git a/tests/scripts/075_path_lookup_dollar0.out b/tests/scripts/075_path_lookup_dollar0.out new file mode 100644 index 0000000..246328a --- /dev/null +++ b/tests/scripts/075_path_lookup_dollar0.out @@ -0,0 +1,45 @@ +-- relative entry +0=./node_modules/.bin/probe +dirname=./node_modules/.bin +source=./node_modules/.bin/probe +-- relative entry, no ./ +0=node_modules/.bin/probe +dirname=node_modules/.bin +source=node_modules/.bin/probe +-- relative entry, trailing slash +0=./node_modules/.bin/probe +dirname=./node_modules/.bin +source=./node_modules/.bin/probe +-- absolute entry +0=/sub/node_modules/.bin/probe +dirname=/sub/node_modules/.bin +source=/sub/node_modules/.bin/probe +-- empty entry (current directory) +0=./probe +dirname=. +source=./probe +-- PATH given as a prefix assignment +0=./node_modules/.bin/probe +dirname=./node_modules/.bin +source=./node_modules/.bin/probe +-- in a pipeline and in the background +0=./node_modules/.bin/probe +dirname=./node_modules/.bin +source=./node_modules/.bin/probe +0=./node_modules/.bin/probe +dirname=./node_modules/.bin +source=./node_modules/.bin/probe +-- npm shim, run from elsewhere +pkg ran: a b +pkg ran: c d +-- typed with a slash: as typed +0=./node_modules/.bin/probe +dirname=./node_modules/.bin +source=./node_modules/.bin/probe +0=node_modules/.bin/probe +dirname=node_modules/.bin +source=node_modules/.bin/probe +-- run as bash script: as given +0=given.sh +dirname=. +source=given.sh diff --git a/tests/scripts/075_path_lookup_dollar0.sh b/tests/scripts/075_path_lookup_dollar0.sh new file mode 100644 index 0000000..ab36fe3 --- /dev/null +++ b/tests/scripts/075_path_lookup_dollar0.sh @@ -0,0 +1,41 @@ +# A script found through PATH gets the path it was found at as $0 (PATH entry + file name), +# so `dirname "$0"` is its folder, as the npm/pnpm shims in node_modules/.bin rely on. +t=$(mktemp -d) +cd "$t" || exit 1 +mkdir -p sub/node_modules/.bin sub/node_modules/pkg/bin +cd sub || exit 1 + +printf '#!/bin/sh\necho "0=$0"\necho "dirname=$(dirname "$0")"\necho "source=${BASH_SOURCE[0]}"\n' > node_modules/.bin/probe +# The shape of the POSIX shims npm, pnpm and yarn write. +printf '#!/bin/sh\nbasedir=$(dirname "$(echo "$0" | sed -e '"'"'s,\\\\,/,g'"'"')")\nexec sh "$basedir/../pkg/bin/run.sh" "$@"\n' > node_modules/.bin/shim +printf 'echo "pkg ran: $*"\n' > node_modules/pkg/bin/run.sh +chmod +x node_modules/.bin/probe node_modules/.bin/shim + +# Absolute paths differ per machine: show them relative to the temp dir. +show() { sed -e "s,$t,,g"; } + +echo "-- relative entry" +(PATH="./node_modules/.bin:$PATH"; probe) +echo "-- relative entry, no ./" +(PATH="node_modules/.bin:$PATH"; probe) +echo "-- relative entry, trailing slash" +(PATH="./node_modules/.bin/:$PATH"; probe) +echo "-- absolute entry" +(PATH="$t/sub/node_modules/.bin:$PATH"; probe) | show +echo "-- empty entry (current directory)" +(cd node_modules/.bin && PATH=":$PATH" && probe) +echo "-- PATH given as a prefix assignment" +PATH="./node_modules/.bin:$PATH" probe +echo "-- in a pipeline and in the background" +(PATH="./node_modules/.bin:$PATH"; probe | cat; probe & wait) +echo "-- npm shim, run from elsewhere" +(PATH="./node_modules/.bin:$PATH"; shim a b) +(PATH="$t/sub/node_modules/.bin:$PATH"; cd / && shim c d) +echo "-- typed with a slash: as typed" +./node_modules/.bin/probe +node_modules/.bin/probe +echo "-- run as bash script: as given" +cp node_modules/.bin/probe given.sh +bash given.sh + +cd / && rm -rf "$t"