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.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
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
| 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 |
| Trying to Tame the Tablet | May 08, 2013 |
- Using Salt Stack and Vagrant for Drupal Development
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- New Products
- RSS Feeds
- New Products
- This is the easiest tutorial
6 hours 8 min ago - Ahh, the Koolaid.
11 hours 46 min ago - git-annex assistant
17 hours 46 min ago - direct cable connection
18 hours 8 min ago - Agreed on AirDroid. With my
18 hours 19 min ago - I just learned this
18 hours 23 min ago - enterprise
18 hours 53 min ago - not living upto the mobile revolution
21 hours 44 min ago - Deceptive Advertising and
22 hours 20 min ago - Let\'s declare that you have
22 hours 21 min ago
Enter to Win an Adafruit Prototyping Pi Plate 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 Prototyping Pi Plate 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
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.



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!