简体   繁体   中英

Pass command line arguments to another command in bash

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?

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: ab , and c . The "Quoted" case processes it as one argument: abc . The "Unquoted" case processes it as 3 arguments: a , b and c . You'll have unhappy users.

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 eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM