Is there any way to take advantage of shell features as quoting and parameter substitution in my own scripts ?
For instance, supose you have to write down a script in order to parse a configuration file (text, not binary). The parameters assigned in it may contain blank chars, so quoting is in mind... You know that Korn shell and Posix shell can parse source lines in order to substitute values and alias before launching commands.
Is it possible to get advantage of these shell features or I have to write down my own parser ?
Thanx in advance
Note: If you are the author of this question and wish to assign points to any of the answers, please login first.For more information on assigning points ,click
here
One way is to leverage the shell's 'read' command with the Inter-Field Separator (IFS). A common use would be reading a colon-delimited file lie '/etc/passwd':
#!/usr/bin/sh
echo "...using COLON as IFS..."
IFS=\:
while read A B C X
do
echo "A=${A} B=${B} C=${C} LEFT=${X}"
done < /etc/passwd
IFS=${OLDIFS}
exit 0
#Give file name as parameter and ensure it can be executed.
file=$1
. $file
echo User $FULL_NAME with Initials $INITIALS on extension $EXT uses $MAIN_FILE
Steve's suggestion to use the "." operator is right on
the mark. However, note that the "." operator uses
PATH, so you may want to temporarily add the
current directory to the head of PATH or require that
the name of the config file is always specified exactly.
Otherwise, if the name of the config file clashes with
a program somewhere in PATH you'll get unexpected
results.
For example, suppose the config file is called "test".
Then if your script does:
cfg="test"
echo FOO
. $cfg
echo BAR
The output will only be FOO, because the "." searches
through the dirs in PATH and will likely find "/usr/bin/test"
before it finds "./test", and "/usr/bin/test" does an "exit"
which will terminate the program. To fix this, try something
like: