简单的有条件意外在bash if语句中失败



我花了很长的时间试图理解为什么下面的" foo"脚本中的第二个条件失败了,但第一个脚本成功了。

请注意:

  • 当前目录包含两个文件:bar and foo。
  • 所有三个字符串$ s1,$ s2和$ s3均根据hexdump相同。

事先感谢您的任何帮助。

session :(在CentOS7主机上运行(:

>ls
bar  foo
>cat foo
#!/bin/bash
s1="bar foo"
s2="bar foo"
s3=`ls`
echo -n $s1 | hexdump -C
echo -n $s2 | hexdump -C
echo -n $s3 | hexdump -C
if [ "$s1" = "$s2" ]; then  # True
    echo s1 = s2
fi
if [ "$s1" = "$s3" ]; then  # NOT true! Why?
    echo s1 = s3
fi
>foo
00000000  62 61 72 20 66 6f 6f                              |bar foo|
00000007
00000000  62 61 72 20 66 6f 6f                              |bar foo|
00000007
00000000  62 61 72 20 66 6f 6f                              |bar foo|
00000007
s1 = s2
>

在回声时引用变量。

echo -n "$s3" | hexdump -C

您会看到文件名之间的新线,因为ls在输出重定向时使用-1

您的演示对echo -n "$s1"等更有说服力,这表明s3中间有一个新线,其中s1s2中有一个空间。不带双引号的echo将新线将newline弄脏到一个空间(通常是字符串中一个或多个白空间字符的每个序列中(。

(。

给定:

#!/bin/bash
s1="bar foo"
s2="bar foo"
s3=`ls`
echo -n "$s1" | hexdump -C
echo -n "$s2" | hexdump -C
echo -n "$s3" | hexdump -C
if [ "$s1" = "$s2" ]; then  # True
    echo s1 = s2
fi
if [ "$s1" = "$s3" ]; then  # NOT true because s3 contains a newline!
    echo s1 = s3
fi

我得到:

$ sh foo
00000000  2d 6e 20 62 61 72 20 66  6f 6f 0a                 |-n bar foo.|
0000000b
00000000  2d 6e 20 62 61 72 20 66  6f 6f 0a                 |-n bar foo.|
0000000b
00000000  2d 6e 20 62 61 72 0a 66  6f 6f 0a                 |-n bar.foo.|
0000000b
s1 = s2
$ bash foo
00000000  62 61 72 20 66 6f 6f                              |bar foo|
00000007
00000000  62 61 72 20 66 6f 6f                              |bar foo|
00000007
00000000  62 61 72 0a 66 6f 6f                              |bar.foo|
00000007
s1 = s2
$

最新更新