This question is a bit vague, hence a lot of the bizarre responses; in fact, some of the answers on this page do not even address the original question whatsoever.
That said, if you want to source (read) a bash variable from a different file, the best solution is always to use a subshell so that no conflicts arise between your script and the file that is being read:
WORKING_VARIABLE=$(source /path/script.sh; echo $FILE_VARIABLE)
We use this method in SlickStack for sourcing the config file multiple times without conflicts.
If you plan to use multiple variables from the file or have other reasons to include the entirety of the other file in your current script, then you might source the entire file:
source /path/script.sh
But in non-bash-variable cases, such as the OP situation of wanting to read a simple "string" from a text file, neither of these solutions would work, and you'd have to use a solution that is tailored to the syntax of the code you are trying to read... for example, one of the examples on this page using grep
or awk
combinations, or @thom solution for reading a given line of a file using read
.
TL;DR subshells are best for bash variables, otherwise it depends on the syntax of the file.... if you want to save the file contents as a bash variable, try cat
as explained by @hellork.
KEY=VALUE
pairs? The solutions are quite different (if it's the latter, Takkat's answer applies, the former Radu's)