[英]How do I make a command a variable
這里是一個相對新手。 我正在使用以下命令讀取文件:
while read line
do
commands here
done < file
我將線分為兩部分,以下用破折號分隔
dash_pos=`expr index "$line" -`
dash_pos
顯然不是常量,這就是為什么我將其dash_pos
變量。
我現在可以執行以下操作
Part1=${line:0:$dash_pos -2}
Part2=${line:$dash_pos + 1}
這些命令按預期方式工作。
有沒有一種方法可以使字符串操作命令成為變量,例如
Find_Part1=${line:0:$dash_pos -2}
Find_Part2=${line:$dash_pos + 1}
以便
Part1=$Find_Part1 & Part2=$Find_Part2
像以前一樣工作,但是它將允許我做
Part1=$Find_Part2 & Part2=$Find_Part1
必要時。
任何幫助將不勝感激,因為我嘗試了各種組合的引號,雙引號,方括號,大括號和反勾號,以嘗試使此方法起作用。 約翰
將可執行代碼存儲在變量中的麻煩遠不止於此。 使用函數代替:
Find_Part1 () {
printf "%s" "${line:0:$dash_pos -2}"
}
Find_Part2 () {
printf "%s" "${line:$dash_pos + 1}"
}
Part1=$(Find_Part1)
Part2=$(Find_Part2)
但是,您似乎真正想要的是
while IFS="-" read Part1 Part2; do
...
done < file
讓read
命令為您將line
分為Part1
和Part2
。
目前尚不清楚為什么您不能僅僅執行問題中的字面意思:
# get the parts
Find_Part1=${line:0:$dash_pos -2}
Find_Part2=${line:$dash_pos + 1}
# ... as necessary:
if such and such condition ; then
Part1=$Find_Part1
Part2-$Find_Part2
else
Part1=$Find_Part2
Part2=$Find_Part1
fi
另外,您可以根據需要交換Part1
和Part2
的值,只需要一個臨時變量
if interesting condition ; then
temp=$Part1; Part1=$Part2; Part2=$temp
fi
在Bash函數內部,我們可能將temp
為local,以避免名稱沖突和名稱空間混亂:
local temp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.