我試圖了解引數擴展在 bash 腳本中的作用。
third_party_bash_script
#!/bin/sh
files="${*:--}"
# For my understanding I tried to print the contents of files
echo $files
pkill bb_stream
if [ "x$VERBOSE" != "" ]; then
ARGS=-v1
fi
while [ 1 ]; do cat $files; done | bb_stream $ARGS
當我運行時./third_party_bash_script,它列印的只是一個連字符-,沒有別的。由于它對我來說沒有意義,我也嘗試在終端中進行試驗
$ set one="1" two="2" three="3"
$ files="${*:--}"
$ echo $files
one="1" two="2" three="3"
$ set four="4"
$ files="${*:--}"
four="4"
我似乎無法理解它在做什么。有人能幫我解釋${*:--}一下sh嗎?
uj5u.com熱心網友回復:
"$@"是傳遞給腳本的引數陣列,"$*"是所有這些引數之間用空格連接的字串。
"${*:--}"是引數字串(如果提供)(:-),-否則表示“從標準輸入獲取輸入”。
"${@:--}"是引數陣列(如果提供)(:-),-否則表示“從標準輸入獲取輸入”。
$ cat file
foo
bar
$ cat tst.sh
#!/usr/bin/env bash
awk '{ print FILENAME, $0 }' "${@:--}"
當一個 arg 被提供給腳本時,"$@"包含"file"所以這是呼叫 awk 的 arg:
$ ./tst.sh file
file foo
file bar
當沒有向腳本提供 arg 時,它"$@"是空的,所以 awk 被呼叫-(意思是從 stdin 讀取),因為它是 arg:
$ cat file | ./tst.sh
- foo
- bar
您幾乎總是想使用"${@:--}"而不是"${*:--}"在這種情況下使用,請參閱https://unix.stackexchange.com/questions/41571/what-is-the-difference-between-and了解有關"$@"vs 的更多資訊"$*"。
uj5u.com熱心網友回復:
${param:-default}擴展為$paramif$param設定且不為空的值,否則擴展為default。
$* 是腳本的所有命令列引數。
在${*:--}、param是*、default是-。如果$*不是空字串,則擴展為腳本引數。如果為空,則擴展為默認值-。
這可以在腳本中使用以實作程式從其引數中列出的檔案中讀取的常見行為,如果沒有給出檔案名引數,則從標準輸入中讀取。許多命令將輸入??檔案名引數-視為代表標準輸入。
uj5u.com熱心網友回復:
注意:解決 OP 的原始、預先編輯的帖子......
有關不同選項的簡要回顧,請參閱shell 引數擴展。
雖然其他答案參考使用${*:--}(and ${@:--}) 作為從 stdin 讀取的替代方法,但 OP 的示例腳本更簡單一些......如果變數$*(即腳本的命令列引數)為空,則用文字 string 替換-。
我們可以通過幾個例子看到這一點:
$ third_party_bash_script
-
$ third_party_bash_script a b c
a b c
$ echo 'a b c' | third_party_bash_script
-
如果我們替換${*:--}為${*:-REPLACEMENT}:
$ third_party_bash_script
REPLACEMENT
$ third_party_bash_script a b c
a b c
$ echo 'a b c' | third_party_bash_script
REPLACEMENT
我猜在 OP 的實際腳本中還有更多關于$files變數的事情,所以為了確定如何${*:--}處理我們需要查看實際腳本以及它如何參考$files變數。
至于 OP 的set|files=|echo代碼片段:
$ set one="1" two="2" three="3"
$ files="${*:--}"
$ echo $files
one=1 two=2 three=3
我們可以從腳本中看到相同的行為:
$ third_party_bash_script one="1" two="2" three="3"
one=1 two=2 three=3
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/391888.html
