0

I'm trying to write a script that's robust enough to work with spaces.

Its currently in a for loop, but the problem I'm having is folders with spaces in its name.

ASOURCE="Home Photos 2012 camcorder" #example filename
if [ -d "$(echo $ASOURCE)" ] # If directory exists
then
#command
else
echo "File does not exist: " $1 #Error
echo "DIR :" $(echo $ASOURCE | sed 's/\ /\\ /g')
fi

It fails on the the verification. I've tried pre-escaping the spaces, but to no avail

  • 3
    First, replace "$(echo $ASOURCE)" with "$ASOURCE", if it doesn't work, at least, it will look nicer. :-) – lgeorget Mar 31 '14 at 14:54
  • well, it looks nicer :P – KG87 Mar 31 '14 at 14:58
  • What shell are you using? This works exactly as expected in bash. Are you actually trying to run this by passing the directory name as an argument? Are you maybe doing this without quoting it? – terdon Mar 31 '14 at 15:59
2

You should always(*) quote your variables, particularly if they contain arbitrary user input.

In this case, if you're scripting with , use double brackets so you don't need to quote (bash is smart that way), and use printf "%q" to get bash to escape what needs to be escaped:

ASOURCE="Home Photos 2012 camcorder" #example filename
if [[ -d $ASOURCE ]]; then
    # directory exists
    :
else
    # Note how these vars are quoted:
    echo "File does not exist:  $1"
    printf "DIR : %q\n" "$ASOURCE"
fi

(*) except when you know exactly when you don't want to quote them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.