Reputation: 18881
I have a program which takes some command line arguments.
It's executed like this:
user@home $ node server.js SOME ARGUMENTS -p PORT -t THEME OTHER STUFF
Now I want to make a executable launcher for it:
#!/bin/bash
node server.js ARGUMENTS GIVEN FROM COMMAND LINE
How to do this?
I want to pass the same arguments to the command (without knowing how many and what they will be).
Is there a way?
Upvotes: 2
Views: 2216
Reputation: 151441
Use the $@
variable in double quotes:
#!/bin/bash
node server.js "$@"
This will provide all the arguments passed on the command line and protect spaces that could appear in them. If you don't use quotes, an argument like "foo bar"
(that is, a single argument whose string value has a space in it) passed to your script will be passed to node
as two arguments. From the documentation:
When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ….
In light of the other answer, edited to add: I fail to see why you'd want to use $*
at all. Execute the following script:
#!/bin/bash
echo "Quoted:"
for arg in "$*"; do
echo $arg
done
echo "Unquoted:"
for arg in $*; do
echo $arg
done
With, the following (assuming your file is saved as script
and is executable):
$ script "a b" c
You'll get:
Quoted:
a b c
Unquoted:
a
b
c
Your user meant to pass two arguments: a b
, and c
. The "Quoted" case processes it as one argument: a b c
. The "Unquoted" case processes it as 3 arguments: a
, b
and c
. You'll have unhappy users.
Upvotes: 7
Reputation: 78523
Depending on what you want, probably using $@
:
#!/bin/bash
node server.js "$@"
(Probably with quotes)
The thing to keep in mind is how arguments with e.g. spaces are handled. In this respect, $*
and $@
behave differently:
#!/usr/bin/env bash
echo '$@:'
for arg in "$@"; do
echo $arg
done
echo '$*:'
for arg in "$*"; do
echo $arg
done
Output:
$ ./test.sh a "b c"
$@:
a
b c
$*:
a b c
Upvotes: 4