我有一個函式,它以不同的組合接受引數。如何設定它們取決于其他條件,所以我創建了一個方法來設定它們。
#!/bin/bash
myFunc(){
while getopts m:t::T::rp:: arg; do
case "$arg"/span> in
m) log_msg="$OPTARG"; 。
t) timeout="$OPTARG";;
T) timeout_msg="$OPTARG";。
r) retry="yes"; 。
p) postpone="$OPTARG";;
*) die "invalid arguments $*"; 。
esac
done; esac.
#doStuff...。
}
setupOpts(){
local name="$1"/span>
local param="$2"。
local err_msg="$3"。
if someTest "$name"/span>; then
# case all; then.
echo "-t 9 -T" $err_msg" -p "$name" -r"
elif someOtherTest "$name"/span> "$param"/span>; then
echo "-t 120 -T"$err_msg" -p "$name"
else
echo "-t 300 -T" $err_msg"
fi。
}
mainFunc() {
# some stuff...
opts="$(setupOpts "$someName"/span> "$someParam" "Some Err Msg") "
myFunc -m "Some Msg" "$opts"
}
我沒有設法讓它作業。例如,當case all(見代碼中的注釋)為真時:
opts="$(setupOpts "peter- pan" "$someParam" "Some Err Msg")"
# -> results in: myFunc -m "some Msg" -t 9 -T "Some Err Msg" -p "peter-pan" -r
但是,-t后面的引數和下面的引數沒有被正確地決議。我猜這與引號和分詞有關。
取決于引號。
視引號而定:
myFunc -m "Some Msg" "$opts":
timeout=9 -T "Some Err Msg"/span> -p "peter-pan"/span> -r
timeout_msg=
postpone=
重試=
或者
myFunc -m "Some Msg" $opts:
timeout=9
timeout_msg=Some
postpone=
重試=
正確的做法是
timeout=9
timeout_msg=一些錯誤資訊
postpone=peter-pan
retry=yes
我試過其他不同的方法,比如使用轉義引號(echo "-t 9 -T ""Some Err Msg"" -p "$argOne" -r")或使用不帶周圍引號的echo。
這在某種程度上是可以用bash來做的,還是我在這里遇到了一個限制?
PS:在myFunc中設定東西也可以,但這不是我答案的解決方案。我想知道這種方法是否能以某種方式在bash中作業。
uj5u.com熱心網友回復:
由于參考的復雜性,你可以使用nameref與陣列相結合:
#!/usr/bin/env bash
myFunc(){
while getopts m:t::T::rp:: arg; do
case "$arg"/span> in
m) log_msg="$OPTARG"; 。
t) timeout="$OPTARG";;
T) timeout_msg="$OPTARG";。
r) retry="yes"; 。
p) postpone="$OPTARG";;
*) die "invalid arguments $*"; 。
esac
done; esac.
#doStuff...。
}
setupOpts(){
local name="$1"/span>
local param="$2"。
local err_msg="$3"
declare -n inner_opts=$4。
if someTest "$name"/span>; then
# case all
inner_opts=(-t 9 -T "$err_msg"/span> -p "$name"/span> -r)
elif someOtherTest "$name"/span> "$param"/span>。then
inner_opts=(-t 120 -T "$err_msg"/span> -p "$name"/span>)
else -p
inner_opts=(-t 300 -T "$err_msg")
fi。
}
mainFunc(){
# some stuff...
local outer_opts
setupOpts "someName" "someParam" "Some Err Msg" external_opts
myFunc -m "Some Msg" "${outer_opts[@]}"
}
主函式(mainFunc)
uj5u.com熱心網友回復:
如果沒有someTest和someOtherTest的定義,我無法重現OP的輸出,所以fwiw ...
(對我來說)看起來,setupOpts()函式生成了一組命令列選項,這些選項將被傳遞給myFunc()函式。假設setupOpts()產生了正確的輸出,我猜想一個解決方案是將setupOpts的輸出存盤在一個陣列中,例如:
opts=( $(setupOpts "peter- pan" "$someParam" "Some Err Msg" )
對myFunc()的主要呼叫就變成:
myFunc -m "Some Msg" "${opts[@]}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/308108.html
標籤:
上一篇:jq提取json的資料
