Please use ***[code][/code]
*** tags around your code and data, to preserve the original formatting and to improve readability. Do not
use quote tags, bolding, colors, "start/end" lines, or other creative techniques. Thanks.
Off the top of my head I can thing of the following ways to import data into a script from an external process.
1) The input parameters
2) Standard In
3) Reading from files or pipes
5) Environment variables
6) Command substitution and process substitution
#2 and #3 are both variations of file descriptors, actually. #6 isn't really a technique on its own, but they are ways to run external commands that can be accessed through stdin or file descriptors.
I'd probably consider the use of them in roughly that order, but it also depends on the exact nature of the code in question. As others have already mentioned, if you only want to input some preset variable settings then simply sourcing the file is probably the best way to go about it.
# content of input.txt
# in the script
. input.txt #source the file
echo "process: $PRC" #use the imported values as desired.
echo "number: $NUM"
echo "name: $NAME"
If you aren't familiar with it, sourcing (the '.
' command, above) means to incorporate the contents of another file into the script and execute it, as if the code was written there directly. For this reason the sourced file must only contain valid shell code.
Incidentally, this is a horribly inefficient way to do what you want. You're using six different external processes, not counting subshells.
PRC=`grep process input.txt |cut -f2 -d'='`
NAME=`grep NAME input.txt |cut -f2 -d'='`
NUM=`grep NUM input.txt |cut -f2 -d'='`
Not to mention that $(..) is highly recommended over `..`
If you absolutely had to parse the values in this way for some reason, just read the file once
and parse the input with shell built-ins.
while IFS='=' read -r tag value ; do
case $tag in
process) PRC=$value ;;
NAME) NAME=$value ;;
NUM) NUM=$value ;;
done < input.txt
Finally, remember to QUOTE ALL OF YOUR VARIABLE EXPANSIONS
. You should never leave the quotes off a parameter expansion unless you explicitly want the resulting string to be word-split by the shell and any possible globbing patterns expanded. This is a vitally important concept in scripting, so train yourself to do it correctly now. You can learn about the exceptions when you need them.