相关疑难解决方法(0)

带有额外空间的多行字符串(保留缩进)

我想使用以下内容将一些预定义的文本写入文件:

text="this is line one\n
this is line two\n
this is line three"

echo -e $text > filename
Run Code Online (Sandbox Code Playgroud)

我期待这样的事情:

this is line one
this is line two
this is line three
Run Code Online (Sandbox Code Playgroud)

但得到了这个:

this is line one
 this is line two
 this is line three
Run Code Online (Sandbox Code Playgroud)

我很肯定每个人都没有空间\n,但额外的空间是如何产生的?

string bash shell echo

353
推荐指数
8
解决办法
39万
查看次数

如何在Bash中为变量分配heredoc值?

我有这个多行字符串(包括引号):

abc'asdf"
$(dont-execute-this)
foo"bar"''
Run Code Online (Sandbox Code Playgroud)

如何在Bash中使用heredoc将其分配给变量?

我需要保留换行符.

我不想逃避字符串中的字符,这会很烦人......

bash heredoc

344
推荐指数
8
解决办法
16万
查看次数

从shell脚本导入函数

我有一个shell脚本,我想用shUnit测试.脚本(和所有功能)都在一个文件中,因为它使安装更容易.

示例 script.sh

#!/bin/sh

foo () { ... }
bar () { ... }

code
Run Code Online (Sandbox Code Playgroud)

我想编写第二个文件(不需要分发和安装)来测试中定义的函数 script.sh

就像是 run_tests.sh

#!/bin/sh

. script.sh

# Unit tests
Run Code Online (Sandbox Code Playgroud)

现在的问题在于.(或source在Bash中).它不仅解析函数定义,还执行脚本中的代码.

由于没有参数的脚本没有任何坏处,我可以

. script.sh > /dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)

但如果有更好的方法来实现我的目标,我就会徘徊.

编辑

我建议的解决方法在源脚本调用的情况下不起作用,exit所以我必须捕获退出

#!/bin/sh

trap run_tests ERR EXIT

run_tests() {
   ...
}

. script.sh
Run Code Online (Sandbox Code Playgroud)

run_tests调用该函数但是只要我重定向source命令的输出,脚本中的函数就不会被解析,并且在陷阱处理程序中不可用

这有效,但我得到的输出script.sh:

#!/bin/sh
trap run_tests ERR EXIT
run_tests() {
   function_defined_in_script_sh
}
. script.sh
Run Code Online (Sandbox Code Playgroud)

这不打印输出但是我得到一个错误,该函数未定义:

#!/bin/sh
trap run_tests ERR EXIT
run_tests() {
   function_defined_in_script_sh
}
. script.sh …
Run Code Online (Sandbox Code Playgroud)

shell

48
推荐指数
3
解决办法
4万
查看次数

标签 统计

bash ×2

shell ×2

echo ×1

heredoc ×1

string ×1