LDP/LDP/guide/docbook/abs-guide/ifs.sh

89 lines
1.5 KiB
Bash
Raw Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
2008-07-20 23:16:47 +00:00
# ifs.sh
2010-03-17 13:43:35 +00:00
var1="a+b+c"
var2="d-e-f"
var3="g,h,i"
IFS=+
# The plus sign will be interpreted as a separator.
echo $var1 # a b c
echo $var2 # d-e-f
echo $var3 # g,h,i
echo
IFS="-"
# The plus sign reverts to default interpretation.
# The minus sign will be interpreted as a separator.
echo $var1 # a+b+c
echo $var2 # d e f
echo $var3 # g,h,i
echo
IFS=","
# The comma will be interpreted as a separator.
# The minus sign reverts to default interpretation.
echo $var1 # a+b+c
echo $var2 # d-e-f
echo $var3 # g h i
echo
IFS=" "
# The space character will be interpreted as a separator.
# The comma reverts to default interpretation.
echo $var1 # a+b+c
echo $var2 # d-e-f
echo $var3 # g,h,i
# ======================================================== #
# However ...
2001-07-10 14:25:50 +00:00
# $IFS treats whitespace differently than other characters.
output_args_one_per_line()
{
for arg
2008-11-23 22:43:47 +00:00
do
echo "[$arg]"
done # ^ ^ Embed within brackets, for your viewing pleasure.
2001-07-10 14:25:50 +00:00
}
echo; echo "IFS=\" \""
echo "-------"
IFS=" "
var=" a b c "
2008-11-23 22:43:47 +00:00
# ^ ^^ ^^^
2001-07-10 14:25:50 +00:00
output_args_one_per_line $var # output_args_one_per_line `echo " a b c "`
# [a]
# [b]
# [c]
echo; echo "IFS=:"
echo "-----"
IFS=:
2008-11-23 22:43:47 +00:00
var=":a::b:c:::" # Same pattern as above,
# ^ ^^ ^^^ #+ but substituting ":" for " " ...
2001-07-10 14:25:50 +00:00
output_args_one_per_line $var
# []
# [a]
# []
# [b]
# [c]
# []
# []
2008-11-23 22:43:47 +00:00
# Note "empty" brackets.
2001-07-10 14:25:50 +00:00
# The same thing happens with the "FS" field separator in awk.
echo
2008-11-23 22:43:47 +00:00
exit