echo 命令是否会自动在输入字符串末尾添加新行字符?

use*_*376 5 bash

所以我刚刚开始学习 bash 脚本。我在一本书上遇到了一个问题。示例测试文件包含以下内容。

$ cat testfile
This is the first line.
This is the second line.
This is the third line.
Run Code Online (Sandbox Code Playgroud)

脚本文件如下:

#!/bin/bash
# testing input/output file descriptor
exec 3<> testfile
read line <&3
echo "Read: $line"
echo "This is a test line" >&3
Run Code Online (Sandbox Code Playgroud)

运行脚本后,测试文件变为:

$ cat testfile
This is the first line.
This is a test line
ine.
This is the third line.
Run Code Online (Sandbox Code Playgroud)

我明白为什么该脚本会更改测试文件。我的问题是为什么“ine”。从新的一行开始?echo 命令会自动在字符串末尾添加换行符吗?

小智 7

echo -n就是您所寻求的:选项 -n 指示 echo“不输出尾随换行符”。

FWIW:man echo在您的平台上将指示 /bin/echo 命令理解哪些选项。但是既然你提到 bash 作为 shell: bash 有一个 echo 的内部实现(所谓的“内置”)