我如何在这里写一个文档到Bash脚本文件?


当前回答

此外,如果您正在写入一个文件,检查写入是否成功或失败可能是一个好主意。例如:

if ! echo "contents" > ./file ; then
    echo "ERROR: failed to write to file" >& 2
    exit 1
fi

要对heredoc进行同样的操作,有两种可能的方法。

1)

if ! cat > ./file << EOF
contents
EOF
then
    echo "ERROR: failed to write to file" >& 2
    exit 1
fi

if ! cat > ./file ; then
    echo "ERROR: failed to write to file" >& 2
    exit 1
fi << EOF
contents
EOF

您可以通过将目标文件./file替换为/file(假设您不是以根用户身份运行)来测试上述代码中的错误情况。

其他回答

如果你想保持heredoc的缩进可读性:

$ perl -pe 's/^\s*//' << EOF
     line 1
     line 2
EOF

Bash中支持缩进式heredoc的内置方法只支持开头制表符,不支持空格。

Perl可以用awk代替,以节省几个字符,但是如果您知道基本的正则表达式,Perl可能更容易记住。

根据@Livven的回答,这里有一些有用的组合。

variable substitution, leading tab retained, overwrite file, echo to stdout tee /path/to/file <<EOF ${variable} EOF no variable substitution, leading tab retained, overwrite file, echo to stdout tee /path/to/file <<'EOF' ${variable} EOF variable substitution, leading tab removed, overwrite file, echo to stdout tee /path/to/file <<-EOF ${variable} EOF variable substitution, leading tab retained, append to file, echo to stdout tee -a /path/to/file <<EOF ${variable} EOF variable substitution, leading tab retained, overwrite file, no echo to stdout tee /path/to/file <<EOF >/dev/null ${variable} EOF the above can be combined with sudo as well sudo -u USER tee /path/to/file <<EOF ${variable} EOF

此外,如果您正在写入一个文件,检查写入是否成功或失败可能是一个好主意。例如:

if ! echo "contents" > ./file ; then
    echo "ERROR: failed to write to file" >& 2
    exit 1
fi

要对heredoc进行同样的操作,有两种可能的方法。

1)

if ! cat > ./file << EOF
contents
EOF
then
    echo "ERROR: failed to write to file" >& 2
    exit 1
fi

if ! cat > ./file ; then
    echo "ERROR: failed to write to file" >& 2
    exit 1
fi << EOF
contents
EOF

您可以通过将目标文件./file替换为/file(假设您不是以根用户身份运行)来测试上述代码中的错误情况。

我喜欢这种方法,因为它简洁、易读,而且在缩进的脚本中表现得很好:

<<-End_of_file >file
→       foo bar
End_of_file

其中→为制表符。

当需要root权限时

当目标文件需要root权限时,使用|sudo tee而不是>:

cat << 'EOF' |sudo tee /tmp/yourprotectedfilehere
The variable $FOO will *not* be interpreted.
EOF

cat << "EOF" |sudo tee /tmp/yourprotectedfilehere
The variable $FOO *will* be interpreted.
EOF