1

I am using the following snippet of code to read file paths into an array;

files=()
while IFS= read -r -d $'\0'; do
    files+=("$REPLY")
done < <(find $dir -type f -print0)

However, when I use print or echo to output each stored file path looping through the array, the spaces are output as normal. I would like to escape them.

some/path/to file -> some/path/to\ file
2
  • 2
    find "$dir", btw, or directory names with spaces will behave badly. Commented Sep 2, 2016 at 22:15
  • Escape them for what purpose? The characters that need to be escaped (and possibly how they need to be escaped) will depend on what'll be interpreting them. Also, if they're for use inside the script, you generally don't want them to be escaped -- instead, just put double-quotes around the variable references (e.g. cp "${files[1]}" "$targetdir") and it'll work correctly. Commented Sep 3, 2016 at 1:58

1 Answer 1

3

For simplicity, let's suppose that we have this array of file names:

files=("some/path/to file")

To display quoted forms of the file names:

$ printf "%q\n" "${files[@]}"
some/path/to\ file

Documentation

From man bash:

%q

causes printf to output the corresponding argument in a format that can be reused as shell input.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.