gpt4 book ai didi

linux - 内嵌shell不支持重定向: exec 2>>(logger -t myscript)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:28:13 26 4
gpt4 key购买 nike

我正在尝试从 this question 运行命令:

exec 2> >(logger -t myscript)

它在我的桌面 linux 系统上运行良好,但是,在我的嵌入式 linux 设备上,相同的命令会出现以下错误:

-sh: syntax error near unexpected token `>'

所以我猜我的 shell 不喜欢命令语法的一部分——很可能是这一部分:

exec 2>>(logger -t myscript)

事实上,虽然我知道 2> 正在重定向 stderr 我实际上并不理解第二个 > 字符的语法在这种情况下,它是表示管道的另一种方式吗?

如果我能理解它在做什么,那么也许我可以修改我的命令以在嵌入式 linux 设备上使用我有限的 shell。

最佳答案

所讨论的语法仅适用于 bash(或其他带有 ksh 扩展名的 shell)。在错误中

-sh: syntax error near unexpected token `>'

...您正在尝试将该语法与 /bin/sh 一起使用.

确保您的脚本以 #!/bin/bash 开头,并且您使用 bash yourscript 调用它而不是 sh yourscript .


更多解释:

  • >(foo)被替换为文件名(如果支持,格式为 /dev/fd/##,否则为命名管道),该文件名接收来自名为 foo 的进程的输出. 这是需要 bash 或 ksh 扩展的部分。
  • exec <redirection>对当前 shell 进程应用重定向(因此,exec 2>stderr.log 将所有 stderr 从当前命令及其子命令重定向到文件 stderr.log)。

因此,exec 2> >(foo)修改(当前 shell session 的)stderr 文件描述符以转到命令 foo 的标准输入;在这种情况下,foologger -t myscript ,从而将进程的标准错误发送到系统日志。


要在更有限(但仍然符合 POSIX)的 shell 上执行相同的操作:

# note: if any security concerns exist, put the FIFO in a directory
# created by mktemp -d rather than hardcoding its name

mkfifo /tmp/log.fifo # create the FIFO
logger -t myscript </tmp/log.fifo & # start the reader in the background first!
exec 2>/tmp/log.fifo # then start writing
rm -f /tmp/log.fifo # safe to delete at this point

关于linux - 内嵌shell不支持重定向: exec 2>>(logger -t myscript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com