在bash shell腳本中傳播所有參數



scripting (5)

我正在編寫一個調用另一個腳本的非常簡單的腳本,並且需要將參數從當前腳本傳播到正在執行的腳本。

例如,我的腳本名稱是foo.sh並調用bar.sh

foo.sh:

bar $1 $2 $3 $4

我怎樣才能做到這一點,沒有明確指定每個參數?


Answer #1

對於bash和其他類似Bourne的砲彈:

java com.myserver.Program "[email protected]"

Answer #2

如果你真的希望你的參數傳遞相同,使用"[email protected]"而不是簡單的[email protected]

注意:

$ cat foo.sh
#!/bin/bash
baz.sh [email protected]

$ cat bar.sh
#!/bin/bash
baz.sh "[email protected]"

$ cat baz.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4

$ ./foo.sh first second
Received: first
Received: second
Received:
Received:

$ ./foo.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:

$ ./bar.sh first second
Received: first
Received: second
Received:
Received:

$ ./bar.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:

Answer #3

使用"[email protected]" (適用於所有POSIX兼容機)。

[...],bash具有“$ @”變量,該變量擴展為用空格分隔的所有命令行參數。

Bash舉例


Answer #4

我的SUN Unix有很多限制,甚至“$ @”也沒有被解釋為需要。 我的解決方法是$ {@}。 例如,

#!/bin/ksh
find ./ -type f | xargs grep "${@}"

順便說一句,我必須擁有這個特定的腳本,因為我的Unix也不支持grep -r


Answer #5

我意識到這已得到很好的回答,但這裡比較了“$ @”$ @“$ *”和$ *

測試腳本的內容:

# cat ./test.sh
#!/usr/bin/env bash
echo "================================="

echo "Quoted DOLLAR-AT"
for ARG in "[email protected]"; do
    echo $ARG
done

echo "================================="

echo "NOT Quoted DOLLAR-AT"
for ARG in [email protected]; do
    echo $ARG
done

echo "================================="

echo "Quoted DOLLAR-STAR"
for ARG in "$*"; do
    echo $ARG
done

echo "================================="

echo "NOT Quoted DOLLAR-STAR"
for ARG in $*; do
    echo $ARG
done

echo "================================="

現在,用各種參數運行測試腳本:

# ./test.sh  "arg with space one" "arg2" arg3
=================================
Quoted DOLLAR-AT
arg with space one
arg2
arg3
=================================
NOT Quoted DOLLAR-AT
arg
with
space
one
arg2
arg3
=================================
Quoted DOLLAR-STAR
arg with space one arg2 arg3
=================================
NOT Quoted DOLLAR-STAR
arg
with
space
one
arg2
arg3
=================================




scripting