【问题标题】:Bash issue with process substitution in a variable变量中进程替换的 Bash 问题
【发布时间】:2023-04-06 13:23:01
【问题描述】:

我正在尝试在 bash 脚本中获取 dd 命令,并将“if”设置为变量。 变量可能是 /dev/zero 或者可能很复杂

我似乎可以让后者工作。

write_file=/dev/zero
dd if=$write_file bs=2048 seek=1 of=/dev/sda count=524288

这行得通。

write_file="<(yes $'\01' | tr -d "\n")"
dd if=$write_file bs=2048 seek=1 of=/dev/sda count=524288

这不起作用。我得到一个

dd: invalid option -- 'd'
Try `dd --help' for more information.

如果我做顺子

dd if=<(yes $'\01' | tr -d "\n") bs=2048 seek=1 of=/dev/sda count=524288

在脚本中它工作正常。

我确定需要进行一些转义,但我还没有 bash 专家来弄清楚如何做到这一点!

更新:尝试以下建议

write_file="<(yes $'\01' | tr -d \"\n\")"
dd if="$write_file" bs=2048 seek=1 of=/dev/sda count=524288

得到了

dd: opening `<(yes $\'\\01\' | tr -d "\\n")': No such file or directory

【问题讨论】:

  • 试试dd "if=$write_file" ...
  • 就行了。见BashFAQ/050

标签: bash process substitution


【解决方案1】:

Bash 不会解析你的变量的内容并直接将它传递给 dd,它不知道如何处理它。 您可以强制 Bash 使用“eval”解析变量:

 write_file="<(yes $'\01' | tr -d \"\n\")"
 command="dd if=$write_file bs=2048 seek=1 of=/dev/sda count=524288"
 eval "${command}"

【讨论】:

  • 好的.. 所以我刚刚发布了自己的答案,然后我刷新了浏览器并看到了这个。哦。哦,好吧,这可能与将eval 放在 dd 命令前面相同。感谢您的帮助!
【解决方案2】:

好的.. 我想我需要在 dd 前面加一个“eval”。

所以:

write_file="<(yes $'\x5a' | tr -d \"\n\")"
eval dd if=$write_file bs=2048 seek=1 of=/dev/sda count=5242

有效!我猜它在执行变量替换或类似的操作后会重新解析。

我从here得到了提示

有趣的是我昨天尝试使用eval,但我无法让它工作。我一定是在某处遗漏了一些引用或转义..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2011-11-05
    • 2015-05-05
    • 1970-01-01
    • 2011-12-02
    • 2021-11-20
    相关资源
    最近更新 更多