Bash: Preserving Whitespace Using set and eval
If you don't care much about whitespace bash is great: it normally turns multiple whitespace characters into one and it breaks things into words based on white space. If on the other hand you'd like to preserve whitespace bash can be a bit difficult at times. A trick which often helps is using a combination of bash's eval and set commands.
Let's say that you're building a list of items where each item may contain significant spaces, say something like:
#!/bin/bash
items=
for i in "$@"
do
items="$items \"$i\""
done
for i in $items
do
echo $i
done
But when you run this and try to use the items from the saved list you don't quite get what you expected:
$ sh t1.sh "ab cd" "ef gh" "ab cd" "ef gh"
One solution is to do the following:
#!/bin/bash
items=
for i in "$@"
do
items="$items \"$i\""
done
eval set -- $items
for i in "$@"
do
echo $i
done
Which produces the desired result:
$ sh t2.sh "ab cd" "ef gh" ab cd ef gh
The important line is:
eval set -- $items
The set command takes any arguments after the options (here "--" signals the end of the options) and assigns them to the positional parameters ($0..$n). The eval command executes its arguments as a bash command.
If you do this without the eval command you'll get the same result as the first example. By passing the set command to eval bash will honor the embedded quotes in the string rather than assume they are part of the word.
If you run this script you can see a bit more of what bash is doing:
#!/bin/bash
items=
for i in "$@"
do
items="$items \"$i\""
done
set -x
set -- $items
set +x
echo '===='
set -x
eval set -- $items
set +x
This produces:
$ sh t3.sh "ab cd" "ef gh" + set -- '"ab' 'cd"' '"ef' 'gh"' + set +x ==== + eval set -- '"ab' 'cd"' '"ef' 'gh"' ++ set -- 'ab cd' 'ef gh' + set +x
Mitch Frazier is an Associate Editor for Linux Journal.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
- RSS Feeds
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- What's the tweeting protocol?
- Tech Tip: Really Simple HTTP Server with Python
- BASH script to log IPs on public web server
4 hours 4 min ago - DynDNS
7 hours 39 min ago - Reply to comment | Linux Journal
8 hours 12 min ago - All the articles you talked
10 hours 35 min ago - All the articles you talked
10 hours 38 min ago - All the articles you talked
10 hours 40 min ago - myip
15 hours 4 min ago - Keeping track of IP address
16 hours 55 min ago - Roll your own dynamic dns
22 hours 9 min ago - Please correct the URL for Salt Stack's web site
1 day 1 hour ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
I dont think I am quite getting eval with arrays!
How about pulling lines from a file into an array while retaining whitespaces on each line? For example:
___________________________________________________________________
#releases.txt
#
CentOS release 5.2 (Final)
CentOS release 5.3 (Final)
CentOS release 5.4 (Final)
Fedora Core release 4 (Stentz)
Fedora Core release 5 (Bordeaux)
Fedora Core release 6 (Zod)
Fedora release 7 (Moonshine)
Fedora release 8 (Werewolf)
Fedora release 9 (Sulphur)
Red Hat Enterprise Linux AS release 4 (Nahant Update 2)
Red Hat Enterprise Linux ES release 3 (Taroon Update 1)
Red Hat Linux release 8.0 (Psyche)
Red Hat Linux release 9 (Shrike)
Ubuntu 2.6.22-14.46-server
Ubuntu 2.6.31-15.50-generic
____________________________________________________________________
so if your array was MYARRAY and the lines where as shown above then $MYARRAY[0] would equal: CentOS release 5.2 (Final)
Would eval work for this or am I barking up the wrong tree?
I guess technically in that
I guess technically in that little file $MYARRAY[0] would equal "#releases.txt" and $MYARRAY[2] would equal: CentOS release 5.2 (Final)
But i think you can get what I am trying to say!
DANGER!!! the eval executes the arguments
try this:
t1.sh "ab cd" "ef \$(pwd) gh"
or
t1.sh "ab cd" 'ef $(pwd) gh'
What about non-quoted?
The IFS seems to fix the multiple space problem:
------------------------
#!/bin/bash
IFS=
while read line
do
echo $line
done
------------------------
This also does not need quoted input.
On the example of reading from a file
Suppose the user types
"ab"
"a b"
"a b"
"a b"
for stdin. We get:
ab
a b
a b
a b
I.e., multiple spaces are reduced to one space.
Embedded Quotes
The example given has problems with inputs that contain quotes
$ t1.sh "foo says, \"bar\""gives
foo says, barTo fix this, the inherent quote in each element needs to be replaced. The resulting script:
#!/bin/bash
items=
for i in "$@"
do
items="$items \"$(echo $i | sed 's/"/\\"/g')\""
done
eval set -- $items
for i in "$@"
do
echo $i
done
gives the desired result:
foo says, "bar"Simple way
A simple way would be to use an array :
items=("$@") for i in "${items[@]}"; do echo $i donexavier
For this example
Using an array is certainly an option in the example I used, but suppose the data with significant spaces is being read from a file or from the terminal such as in this example:
If the user types "ab cd" "ef gh" and we'd like to display ab cd and ef gh (without quotes) then you need eval. Another alternative that does use arrays is the following:
Mitch Frazier is an Associate Editor for Linux Journal.
Thanks for clarifying that
Thanks for clarifying that part!