bash 评估和字符串“返回”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7350658/
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-18 00:44:06  来源:igfitidea点击:

eval and string "return"

stringbashevalreturn-value

提问by MSC29

Edit: I'm creating a bash script to run Netezza queries.

编辑:我正在创建一个 bash 脚本来运行 Netezza 查询。

here's an example of what I have to do:

这是我必须做的一个例子:

nzsql -host localhost -port 123456 -d db -u usr -pw pwd -A -t -c "insert into TABLE (name,surname) values ('m','sc')"

and it should return

它应该返回

INSERT 0 1

What I need is retrieve the number "1" which means that 1 row was inserted.

我需要的是检索数字“1”,这意味着插入了 1 行。

For this, I'd need to retrieve the whole string "INSERT 0 1" and work on it.

为此,我需要检索整个字符串“INSERT 0 1”并对其进行处理。

according to http://www.enzeecommunity.com/thread/2423this should work:

根据http://www.enzeecommunity.com/thread/2423这应该有效:

cmnd_output=`nzsql -host $NZ_HOST -d $NZ_DATABASE -u $NZ_USER -pw $NZ_PASSWORD -A -t -c "insert into TEST values ('test 1')"`

But I can't get it to work with this: ($2 is right because when I run it from the terminal it works just fine)

但我无法让它工作:($ 2 是正确的,因为当我从终端运行它时,它工作得很好)

cmd_out=`` or cmd_out=`""` or cmd_out="``" or cmd_out=`"''"`
cmd_out=$() or cmd_out="$()" or cmd_out=$("")

It tells me command not found... just like if there was a "string quote" problem with $2

它告诉我找不到命令……就像 $2 存在“字符串引用”问题一样

I've however managed to execute $2 with eval

然而,我设法用 eval 执行了 $2

eval ""

and it works great, the command $2 is executed just fine. But, I can't use eval in this case as I want to store in a variable that "INSERT 0 1".

它工作得很好,命令 $2 执行得很好。但是,在这种情况下我不能使用 eval,因为我想存储在“INSERT 0 1”的变量中。

回答by Marc B

A simple

一个简单的

variable_int=`$function '$arg1' '$arg2'`

without the eval won't do?

没有 eval 不行吗?

回答by bash-o-logist

To assign return values from functions to a shell variable, use command substitution

要将函数的返回值分配给 shell 变量,请使用命令替换

variable=$(function arg1 arg2)

Why do you need eval?

你为什么需要eval

回答by Paul Rubel

When you run into a problem like this I find it's always very useful to run with the -x option, just change the top sh-bang line like so:

当您遇到这样的问题时,我发现使用 -x 选项运行总是非常有用,只需像这样更改顶部的 sh-bang 行:

#!/bin/bash -x

That'll print out each line as it's currently interpreted before executing it. You can see how your variables are being mangled and use that to fix the problem.

这将在执行之前打印出当前解释的每一行。您可以查看变量是如何被破坏的,并使用它来解决问题。