bash 将结果从 FIND 命令导出到 linux shell 脚本中的变量值?

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

Export result from FIND command to variable value in linux shell script?

linuxbashshellvariables

提问by black_hat_cat

I try to complete one shell script, but I don't have idea how to do final, and probably easiest step.

我尝试完成一个 shell 脚本,但我不知道如何完成最后一步,也可能是最简单的一步。

That is attaching value to variable from find command.

那是将值附加到 find 命令中的变量。

For example, if I execute:

例如,如果我执行:

find -type f -iname *test.tdf*

I will get output in example:

我将在示例中获得输出:

/root/Desktop/test.tdf

Now, I need a way to attach that value to for example:

现在,我需要一种方法来将该值附加到例如:

export PATH_TO_TEST_TDF_FILE=/root/Desktop/test.tdf

But now, problem is that file may not be located there, so I must assign it to result from find.

但是现在,问题是文件可能不在那里,所以我必须将它分配给 find 的结果。

How?

如何?

回答by iruvar

If your findinvocation outputs a single file along the lines of what you have shown, command substitutionshould do the trick

如果您的find调用按照您显示的内容输出单个文件,则命令替换应该可以解决问题

export PATH_TO_TEST_TDF_FILE="$(find . -type f -iname '*test.tdf*')"

Or, as BroSlowpoints out,

或者,正如BroSlow指出的那样,

export PATH_TO_TEST_TDF_FILE="$(find . -type f -iname '*test.tdf*' -print -quit)"

to have findquit after the first file

已经find第一个文件后退出

回答by Joshua

Would be PATH_TO_TEST_TDF_FILE="$(find -type f -iname test.tdf)" but probably doesn't work too well as find returns more than one file most of the time.

将是 PATH_TO_TEST_TDF_FILE="$(find -type f -iname test.tdf)" 但可能效果不佳,因为 find 大部分时间都返回多个文件。

Pro tip: The results of find should be assumed to not fit in a variable until proven otherwise.

专业提示:应该假设 find 的结果不适合变量,除非另有证明。