Skip to content

Commit 5cc8609

Browse files
committed
nix run: Allow passing a command to execute
E.g. nix run nixpkgs.hello -c hello --greeting Hallo Note that unlike "nix-shell --command", no quoting of arguments is necessary. "-c" (short for "--command") cannot be combined with "--" because they both consume all remaining arguments. But since installables shouldn't start with a dash, this is unlikely to cause problems.
1 parent 93a5ef0 commit 5cc8609

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

src/libutil/args.cc

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,11 @@ bool Args::processFlag(Strings::iterator & pos, Strings::iterator end)
102102
++pos;
103103
Strings args;
104104
for (size_t n = 0 ; n < flag.arity; ++n) {
105-
if (pos == end)
105+
if (pos == end) {
106+
if (flag.arity == ArityAny) break;
106107
throw UsageError(format("flag '%1%' requires %2% argument(s)")
107108
% name % flag.arity);
109+
}
108110
args.push_back(*pos++);
109111
}
110112
flag.handler(args);

src/libutil/args.hh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ public:
2626

2727
protected:
2828

29+
static const size_t ArityAny = std::numeric_limits<size_t>::max();
30+
2931
/* Flags. */
3032
struct Flag
3133
{

src/nix/run.cc

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,20 @@ std::string chrootHelperName = "__run_in_chroot";
1717

1818
struct CmdRun : InstallablesCommand
1919
{
20+
Strings command = { "bash" };
21+
2022
CmdRun()
2123
{
24+
mkFlag()
25+
.longName("command")
26+
.shortName('c')
27+
.description("command and arguments to be executed; defaults to 'bash'")
28+
.arity(ArityAny)
29+
.labels({"command", "args"})
30+
.handler([&](Strings ss) {
31+
if (ss.empty()) throw UsageError("--command requires at least one argument");
32+
command = ss;
33+
});
2234
}
2335

2436
std::string name() override
@@ -43,8 +55,8 @@ struct CmdRun : InstallablesCommand
4355
unixPath.push_front(path + "/bin");
4456
setenv("PATH", concatStringsSep(":", unixPath).c_str(), 1);
4557

46-
std::string cmd = "bash";
47-
Strings args = { cmd };
58+
std::string cmd = *command.begin();
59+
Strings args = command;
4860

4961
/* If this is a diverted store (i.e. its "logical" location
5062
(typically /nix/store) differs from its "physical" location

0 commit comments

Comments
 (0)