shell bash和dash之间的意外差异,在命令替换中解释换行符[重复]

3xiyfsfu  于 2023-08-07  发布在  Shell
关注(0)|答案(1)|浏览(112)

此问题在此处已有答案

How can I 'echo' out things without a newline?(5个答案)
Echo newline in Bash prints literal \n(22个回答)
9天前关闭。
截至9天前,社区正在审查是否重新讨论这个问题。
我遇到过bash和dash之间行为上的一个奇怪差异,其中引用的命令替换与换行符有一些差异。
我不确定这种行为是否是故意的,但我怀疑这不是因为bash和dash都符合posix,这似乎是相当核心的行为。
首先,我创建一个数据文件:

$ echo '"\n"' > data.txt

字符串
要确认文件中的字节数,我可以运行:

$ xxd data.dat
00000000: 225c 6e22 0a                             "\n".


然后,我运行以下bash脚本:

#!/bin/bash

data=$(cat data.txt)
echo "$data"


输出为:

$ ./test.bash
"\n"


然后运行以下dash脚本。它与bash脚本相同,但运行在dash而不是bash中:

#!/bin/dash

data=$(cat data.txt)
echo "$data"


输出为:

$ ./test.dash
"
"


我认为两个不同的shell之间的行为应该是相同的,但事实并非如此。有谁知道为什么行为不同吗?
我运行的dash版本是:

$ dpkg -s dash
Package: dash
Essential: yes
Status: install ok installed
Priority: required
Section: shells
Installed-Size: 199
Maintainer: Andrej Shadura <andrewsh@debian.org>
Architecture: arm64
Multi-Arch: foreign
Version: 0.5.12-2
Depends: debianutils (>= 5.6-0.1), dpkg (>= 1.19.1)
Pre-Depends: libc6 (>= 2.34)
Description: POSIX-compliant shell
 The Debian Almquist Shell (dash) is a POSIX-compliant shell derived
 from ash.
 .
 Since it executes scripts faster than bash, and has fewer library
 dependencies (making it more robust against software or hardware
 failures), it is used as the default system shell on Debian systems.
Homepage: http://gondor.apana.org.au/~herbert/dash/


我运行的bash版本是:

$ bash --version
GNU bash, version 5.2.15(1)-release (aarch64-unknown-linux-gnu)
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

dxxyhpgq

dxxyhpgq1#

这是因为echo在shell中内置了命令。所以不同的shell对同一个命令有不同的实现。最好使用printf来定义你想看到什么以及如何看到这些东西。
或者按照注解中的建议使用操作系统可执行文件:

/usr/bin/echo.....

字符串

相关问题