Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get variable from text file into Bash variable

Tags:

bash

kill

pid

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

#!/bin/sh PIDFile="/var/run/app_to_kill.pid" CurPID=(<$PIDFile)  kill -9 $CurPID 
like image 819
AndyW Avatar asked Dec 30 '11 21:12

AndyW


People also ask

How do I read a variable from a file?

To read variables from a file we can use the source or . command. You can use sed to add local keyword and make the script a bit safer and not polute your global scope. So inside a a function do cat global_variables.sh | sed -e 's/^/local /' > local_variables.sh and then use . ./local_variables.sh .

How do you store a file in a variable in Linux?

One way we can write variable contents to a file is to use the echo command along with the redirect operator. In this case, the -e argument applies to the call to echo and is not sent as output to the file. So we only see “some value”.


1 Answers

You're almost there:

CurPID=$(<"$PIDFile") 

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

kill -9 $(<"$PIDFile") 
like image 119
SiegeX Avatar answered Sep 18 '22 19:09

SiegeX