[英]How to pass a file as an argument to a bash script function?
我試圖編寫一個腳本來編輯腳本功能內的文件,並使用作為參數傳遞的文件名將其保存為新文件,以命名新文件。 這是我所擁有的一個例子:
renamer () {
temp="$1"
echo a test >> temp
cat $temp > new.$1
}
echo this is > b
renamer b
我想要一個名為new.b的文件,其中包含“ this is a test”,但是我的文件中只有“ this is”。 我在這里想念什么嗎?
正如其他人所說,要獲取變量的值 ,您需要在變量名前添加一元運算符$
。 嘗試與您的引用(如果有疑問,請引用它)保持一致,並縮進函數內部的代碼(以及if
, while
循環等),所有有經驗的程序員都應這樣做。
renamer () {
# Indenting makes the code easier to read
# copying positional parameters to a named parameter (variable)
# is a good thing, but be consistent
temp="$1"
# Adding quotes preserves additional whitespace in the text
# and preserves whitespace in the filename
echo "a test" >> "$temp"
# Probably better to use cp(1)
# You used $temp before, so why not here too?
# Should this copy be done first? See the comment by @tripleee
cp "$temp" "new.$temp"
}
# Preserve additional whitespace in the text by quoting
echo "this is" > b
renamer b
您可能會合理地說,我的建議是更多的工作,但是當您處理更大,更復雜的腳本時,編碼學科將在以后有所作為。
您在臨時工前面缺少美元符號
echo a test >> $temp
沒有美元符號,bash會按字面意義解釋字符串“ temp”,而不是將其解釋為變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.