我有一个 bash 函数
yumtelegraf() {
cat <<EOF | sudo tee /etc/yum.repos.d/influxdb.repo
[influxdb]
name = InfluxDB Repository - RHEL \$releasever
baseurl = https://repos.influxdata.com/rhel/\$releasever/\$basearch/stable
enabled = 1
gpgcheck = 1
gpgkey = https://repos.influxdata.com/influxdb.key
EOF
sudo yum install telegraf
}
如果我在函数中使用缩进,它将打印制表符空格到文件...
yumtelegraf() {
cat <<EOF | sudo tee /etc/yum.repos.d/influxdb.repo
[influxdb]
name = InfluxDB Repository - RHEL \$releasever
baseurl =
https://repos.influxdata.com/rhel/\$releasever/\$basearch/stable
enabled = 1
gpgcheck = 1
gpgkey = https://repos.influxdata.com/influxdb.key
EOF
sudo yum install telegraf
}
如何避免这种行为?
这也可以用 echo 命令实现吗?
答案1
使用制表符和<<-EOF
(带有破折号)或使用过滤器而不是 cat,例如。sed
:
$ sed -e "s/^\s*//" <<EOF
as
df
gh
jk
op # two tabs
EOF
这会删除空格和制表符。请注意,结尾EOF
不能缩进。您可以使用<<" EOF"
和 ,然后再次使用" EOF"
与结束标记相同数量的空格,但引号会阻止此处文档中的扩展,在本例中您不希望这样做。比较:
$ a=x
$ cat <<EOF
"$a"
EOF
"x"
$ cat <<"EOF"
"$a"
EOF
"$a"
至于echo
它有这个问题。但您printf
也可以使用:
printf "%s\n" \
"[influxdb]" \
"name = InfluxDB Repository - RHEL \$releasever" \
"baseurl = https://repos.influxdata.com/rhel/\$releasever/\$basearch/stable" \
"enabled = 1" \
"gpgcheck = 1" \
"gpgkey = https://repos.influxdata.com/influxdb.key" \
| sudo tee /etc/yum.repos.d/influxdb.repo
我在你的问题中留下了破折号\$
,但它们在这里可能不正确,因为它们正在逃避扩展。
答案2
您需要使用<<-
(注意-
)来专门启用您想要的功能。
yumtelegraf() {
cat <<-EOF | sudo tee /etc/yum.repos.d/influxdb.repo
[influxdb]
name = InfluxDB Repository - RHEL \$releasever
baseurl =
https://repos.influxdata.com/rhel/\$releasever/\$basearch/stable
enabled = 1
gpgcheck = 1
gpgkey = https://repos.influxdata.com/influxdb.key
EOF
sudo yum install telegraf
}
答案3
您可以使用echo -e "\tblabla"
:
$ echo -e "\tblabla\n\t\tblibli\n\t\t\tbloblo\n"
blabla
blibli
bloblo
正如 bash 手册页中所解释的:
If the -e option is given, interpretation of the following backslash-escaped characters is enabled.
[...]
\a alert (bell)
\b backspace
\c suppress further output
\e
\E an escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\0nnn the eight-bit character whose value is the octal value nnn (zero to three octal digits)
\xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)
\uHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits)
\UHHHHHHHH
the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits)