bash - shell script參數傳入




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

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

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

Bash舉例

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

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

foo.sh:

bar $1 $2 $3 $4

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


如果你真的希望你的參數傳遞相同,使用"[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:

工作正常,除非你有空格或轉義字符。 我沒有找到在這種情況下捕獲參數的方法,並發送到腳本內的ssh。

這可能是有用的,但非常難看

_command_opts=$( echo "[email protected]" | awk -F\- 'BEGIN { OFS=" -" } { for (i=2;i<=NF;i++) { gsub(/^[a-z] /,"&@",$i) ; gsub(/ $/,"",$i );gsub (/$/,"@",$i) }; print $0 }' | tr '@' \' )

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

測試腳本的內容:

# 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
=================================

#!/usr/bin/env bash
while [ "$1" != "" ]; do
  echo "Received: ${1}" && shift;
done;

試想在測試參數如何進入腳本時,這可能會更有用





scripting