tags:

views:

252

answers:

3

I have inherited a shell script. One of the things it does is parsing of a list of filenames. For every filename in the list it does following command:

fs_item="`echo ${fs_item%/}`"

This command (a part from doing it's job which in this case, I think, is to remove everything after last slash) replaces spaces in filename with one space:

in:  aa bbbb              ccc
out: aa bbbb ccc

From this point filename is broken.

So, the question is: can I somehow tell bash not to replace spaces?

A: 

Is the echo really necessary? You could simply remove it:

fs_item="${fs_item%/}"

If your actual problem is something different, and you cannot get rid of the echo (or some other command invocation), adding some quotes should work:

fs_item="`echo \"${fs_item%/}\"`"

The spaces vanish when running the backticked echo command. The internal field separator includes the space character, so words separated by a sequence of one or more spaces will be passed as separate arguments to echo. Then, echo just prints it's arguments separated by a single space.

Since we're on the internal field separator subject, changing the IFS should also work (but usually has other possibly undesirable effects elsewhere in your script):

IFS=$'\n'

This sets the internal field separator to the newline character. After this, the spaces are no longer considered to be separators for lists. The echo command will receive just one argument (unless you have file names with the newline character in them) and spaces will stay intact.

Ville Laurikari
Adding quotes just adds an additional layer of obfuscation. The echo needs to be purged.
William Pursell
Based on comments in the original question I suspect the actual problem apparently may not be possible to simplify like that. But fair enough, I'll mention this in my post as well.
Ville Laurikari
A: 

Try setting IFS to something else, e.g. IFS=","

bdijkstra
+1  A: 

Get rid of the backticks and the echo command. It is worse than useless in this situation because it adds nothing, and causes the problem you are trying to solve here.

fs_item="${fs_item%/}"
camh