如何从文本文件中获取变量到 Bash 变量中

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

How to get variable from text file into Bash variable

bashkillpid

提问by AndyW

Simple question, in BASH I'm trying to read in a .pid file to kill a process. How do I read that file into a variable. All the examples I have found are trying to read in many lines. I only want to read the one file that just contains the PID

一个简单的问题,在 BASH 中,我试图读取 .pid 文件以终止进程。如何将该文件读入变量。我发现的所有例子都试图在多行中阅读。我只想读取一个只包含 PID 的文件

#!/bin/sh
PIDFile="/var/run/app_to_kill.pid"
CurPID=(<$PIDFile)

kill -9 $CurPID

回答by SiegeX

You're almost there:

您快到了:

CurPID=$(<"$PIDFile")

In the example you gave, you don't even need the temp variable. Just do:

在您给出的示例中,您甚至不需要临时变量。做就是了:

kill -9 $(<"$PIDFile")

回答by gavenkoa

POSIX portable way:

POSIX 便携方式:

$ read pid <$pidfile

See: pid=`cat $pidfile` or read pid <$pidfile?

请参阅:pid=`cat $pidfile` 或读取 pid <$pidfile?