[英]How to pass a file as an argument to a bash script function?
I am trying to write a script to edit files within a function of a script, and save them as new files, using the name of the file passed as an argument to name the new file. 我试图编写一个脚本来编辑脚本功能内的文件,并使用作为参数传递的文件名将其保存为新文件,以命名新文件。 This is an example of what i have:
这是我所拥有的一个例子:
renamer () {
temp="$1"
echo a test >> temp
cat $temp > new.$1
}
echo this is > b
renamer b
I want a file named new.b which contains "this is a test" in it, but my file just has "this is" in it. 我想要一个名为new.b的文件,其中包含“ this is a test”,但是我的文件中只有“ this is”。 Am I missing something here?
我在这里想念什么吗?
As others have said, to get the value of a variable you need to prefix the variable name with the unary operator $
. 正如其他人所说,要获取变量的值 ,您需要在变量名前添加一元运算符
$
。 Try to be consistent with your quoting (if in doubt, quote it), and indent code inside functions (and if
, while
loops, etc.) all experienced programmers do that. 尝试与您的引用(如果有疑问,请引用它)保持一致,并缩进函数内部的代码(以及
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
You might reasonably say that what I suggest is more work, but coding discipline will pay dividends later when you are dealing with larger and more complex scripts. 您可能会合理地说,我的建议是更多的工作,但是当您处理更大,更复杂的脚本时,编码学科将在以后有所作为。
You are missing a dollar sign in front of temp 您在临时工前面缺少美元符号
echo a test >> $temp
Without the dollar sign, bash is interpreting the string "temp" literally and not as a variable 没有美元符号,bash会按字面意义解释字符串“ temp”,而不是将其解释为变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.