使用>|有什么意义当重定向到 /dev/null 时?

问题描述 投票:0回答:1

我正在查看 GitHub 文档中的 Bash 文件。摘录如下:

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

我对编码选择有很多疑问。我不确定这是否是混乱的代码,或者做出的决定是否有我可以了解的原因:

  1. 使用
    >|
    强制重定向到
    /dev/null
    有什么意义?
    noclobber
    不是与
    /dev/null
    无关吗?
  2. 在每个函数的最后一行后添加分号有什么目的吗?这是否在某种程度上确保了代码安全?
  3. 第二个函数的奇怪括号格式和另一个函数的单行函数是怎么回事?这只是糟糕的编码标准还是有适用于此的 shell 脚本约定?我的直觉是统一格式化所有函数以提高可读性,如下所示:
function myfunc() {
    # ...
}
bash shell standards conventions
1个回答
0
投票
  1. >|
    用于重定向:

>|
运算符用于在 Bash 中进行破坏,这意味着它将 如果文件已存在,则覆盖该文件,即使使用
noclobber
选项 已设置。在提供的代码中,它与
/dev/null
。虽然你是对的, noclobber 与
/dev/null
,在这种情况下使用
>|
可以确保 重定向到
/dev/null
不会受到
noclobber
的影响 选项。这是一种明确说明覆盖 if 的意图的方法 文件存在。

  1. 函数末尾的分号:

在 Bash 中每个函数末尾的分号不是必需的。在 大多数情况下,它没有任何特定目的。这很可能只是 风格选择。在 Bash 中,分号用于分隔命令 同一行,并且由于这些中每行只有一个命令 函数,技术上不需要分号。

  1. 括号格式:

第二个函数中括号的使用`(umask 077; ssh-agent

| “$env”)

creates a
subshell
. This is done to limit the scope of the 
umask
command so that it doesn't affect the rest of the script. The output of the
ssh-agent
command is then redirected to the file specified by
$env`。这种做法是合理的,并且遵循一个共同的原则 shell 脚本中的模式。

© www.soinside.com 2019 - 2024. All rights reserved.