Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Bash script not playing nice with spaces.

I need my bash script to be able to properly work with files/folders that have spaces in them.


The script below does exactly what I need to do to if there are no spaces in file or folder names. When it encounters a space, it treats everything after it as a seperate argument.


I've been hunting high and low for answers, and my google-fu has nothing left.


#!/bin/bash


export VAR=$(find /disk -type d -name "My Files")


for i in "$VAR" ; do


rsync -avR $i /iscsi;

rm -r $i;

ln -s /iscsi/$i $i;


done


If anyone know of a better way to do this, I'm open to suggestions.

Mac OS X (10.7.2)

Posted on Nov 28, 2011 2:32 PM

Reply
4 replies

Nov 28, 2011 8:03 PM in response to Flex_Brannigan

Linc Davis' approach is what I typically use, however, just for fun, I'm presenting an alternate way to do the same thing:


#!/usr/bin/env bash

while read file

do

rsync -avR "${file}" /iscsi;

rm -r "${file}";

ln -s /iscsi/"${file}" "${file}";

done < <(find /disk -type d -name "My Files")


NOTE: the < < is NOT <<. There is a space between the first < and the second < which is special bash foo.


The advantage of <(...) is that any variables set inside the loop are available outside the loop. Using command|while loop has the negative side effect that any variables set inside the while loop are lost when the loop terminates. This is because the command|while loop runs the while loop in a subprocess, and when the subprocess terminates, its environment is gone.


In your case, you do not need to preserve any variables from the loop, so Linc Davis' approach is a very good choice, as it is easy to understand, is commonly used, and it works under many different shells. The <(...) approach is limited to the bash shell.

Bash script not playing nice with spaces.

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.