【问题标题】:How to pass a file as an argument to a bash script function?如何将文件作为参数传递给 bash 脚本函数?
【发布时间】:2019-11-06 13:21:52
【问题描述】:

我正在尝试编写一个脚本来编辑脚本函数中的文件,并将它们保存为新文件,使用作为参数传递的文件名来命名新文件。这是我所拥有的一个例子:

renamer () {

temp="$1"
echo a test >> temp
cat $temp > new.$1

 }

echo this is > b

renamer b

我想要一个名为 new.b 的文件,其中包含“这是一个测试”,但我的文件中只有“这是”。我在这里错过了什么吗?

【问题讨论】:

  • 追加第二行时需要"$temp",而不是文字文件名temp
  • 复制修改后的文件似乎是错误的。要么生成一个新文件然后修改它,要么重命名修改后的文件并丢失原始文件。

标签: bash function file arguments


【解决方案1】:

你在 temp 前面少了一个美元符号

echo a test >> $temp

没有美元符号,bash 将字符串“temp”从字面上解释为变量,而不是变量

【讨论】:

    【解决方案2】:

    正如其他人所说,要获取变量的,您需要在变量名前加上一元运算符$。尝试与您的引用保持一致(如果有疑问,请引用它),并在函数内缩进代码(以及 ifwhile 循环等)所有有经验的程序员都会这样做。

    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
    

    您可能会合理地说我的建议是更多的工作,但是当您处理更大和更复杂的脚本时,编码纪律会带来好处。

    【讨论】:

      猜你喜欢
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      • 2017-09-26
      • 2012-01-23
      • 1970-01-01
      • 2020-03-24
      相关资源
      最近更新 更多