2

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I mentioned $* because it's often used by bash beginners instead of $@.
The In light of the other answer part is a kinda confusing (not really part of an answer), but I'll give this to you since you came earlier. Thanks.
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.