I am having a problem with my bash script -- And I think honestly it's a matter of understanding IFS completely.
I have read multiple questions on SO but seem to be going in circles I think because none address the issue specifically having to do with MySQL ... But I'll defer to your expertise on that. First here is the script I am having trouble with:
#!/bin/bash
mysql --login-path=main-data -Nse "SELECT b.name, a.section_id
FROM some_table" | while read section_name section_id; do
echo "$section_name - $section_id"
mysql --login-path=main-data -Nse "SELECT a.page_id, b.page_url
FROM some_table" | while read page_id page_url; do
echo " - $page_url";
done
get_children() {
mysql --login-path=main-data -Nse " SELECT b.sections_id, b.name
FROM some_table" | while read child_id section_name; do
echo " -- $section_name";
# If statement goes here -- Then recursive
if [[ $child_id = *[!\ ]* ]]; then
section_id=$child_id
# Now get pages for child sections
mysql --login-path=main-data -Nse "SELECT page_id, page_url
FROM some_table" | while read page_id page_url; do
echo " - $page_url";
done
get_children $section_id
fi
done
}
get_children $section_id
done
If I run my script without IFS as-is the output looks like:
HOME - 732
- Home.htm
- Home2.htm
- Nome3.htm
WHY - US 742
ROOFING - 743
- Residential-Roofing.htm
-- Certainteed
- CertOverview.htm
The issue comes with "WHY US" -- If you notice the dash ended up in the wrong spot -- Obviously a delimiter issue because there is a space there .. Now if I change the first loop to :
mysql --login-path=main-data -Nse "SELECT a.page_id, b.page_url
FROM some_table" | while IFS='\n' read page_id page_url; do
My output becomes :
HOME 732 -
WHY US 742 -
ROOFING 743 -
Which you'll notice the dashes are ALL in the wrong spot but "WHY US" has the correct space in it. In addition to that my nested loops did not run. I am thoroughly confused about the "correct" way to deal with spaces in these names, and still get the desired nested output! Where am I going wrong?
RESOURCES
SO QUESTION This one addresses IFS while nested, but in the wrong context, unusable
SO QUESTION Again same issue ... Obviously I tried what they have in the answer section to no avail.
IFS, you should change it for as small a section of the script as possible to minimize unexpected side effects. In this case, if @KamilCuk's suggestion does solve it, you probably want to changeIFSonly for thereadcommands. You can do this by making the assignment a prefix to thereadcommand, like this:... | while IFS=$'\t' read ...while IFS=$'\t' readand the output looks still like the second "un-nested" result