在 bash 脚本中连接字符串(与 shell 不同的行为)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5882646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:56:00  来源:igfitidea点击:

Concatenate strings inside bash script (different behaviour from shell)

linuxbashstring

提问by Rorro

I'm trying some staff that is working perfectly when I write it in the regular shell, but when I include it in a bash script file, it doesn't. First example:

当我在常规 shell 中编写它时,我正在尝试一些工作正常的工作人员,但是当我将它包含在 bash 脚本文件中时,它没有。第一个例子:

m=`date +%m`
m_1=$((m-1))
echo $m_1

This gives me the value of the last month (actual minus one), but doesn't work if its executed from a script.

这给了我上个月的值(实际减去一),但如果它从脚本执行则不起作用。

Second example:

第二个例子:

m=6
m=$m"t"
echo m

This returns "6t" in the shell (concatenates $m with "t"), but just gives me "t" when executing from a script.

这会在 shell 中返回“6t”(将 $m 与“t”连接起来),但在从脚本执行时只给我“t”。

I assume all these may be answered easily by an experienced Linux user, but I'm just learning as I go.

我认为经验丰富的 Linux 用户可以轻松回答所有这些问题,但我只是在学习。

Thanks in advance.

提前致谢。

回答by hmontoliu

Re-check your syntax.

重新检查您的语法。

Your first code snippet works either from command line, from bashand from shsince your syntax is valid sh. In my opinion you probably have typos in your script file:

您的第一个代码片段可以从命令行bashsh 运行,因为您的语法是有效的 sh。我认为您的脚本文件中可能有拼写错误:

~$ m=`date +%m`; m_1=$((m-1)); echo $m_1
4
~$ cat > foo.sh
m=`date +%m`; m_1=$((m-1)); echo $m_1
^C
~$ bash foo.sh
4
~$ sh foo.sh
4

The same can apply to the other snippet with corrections:

这同样适用于其他带有更正的代码片段:

~$ m=6; m=$m"t"; echo $m
6t
~$ cat > foo.sh
m=6; m=$m"t"; echo $m
^C
~$ bash foo.sh
6t
~$ sh foo.sh
6t

回答by Sven Marnach

Make sure the first line of your script is

确保脚本的第一行是

#!/bin/bash

rather than

而不是

#!/bin/sh

Bash will only enable its extended features if explicitly run as bash. If run as sh, it will operate in POSIX compatibility mode.

Bash 只会在显式运行时启用其扩展功能bash。如果作为 运行sh,它将在 POSIX 兼容模式下运行。

回答by Matt

First of all, it works fine for me in a script, and on the terminal. Second of all, your last line, echo mwill just output "m". I think you meant "$m"..

首先,它在脚本和终端上对我来说都很好。其次,你的最后一行echo m只会输出“m”。我想你的意思是“$m”..