makansij
makansij

Reputation: 9865

How to make bash script take file names with spaces?

I have a bash script like this:

myfiles=("file\ with\ spaces.csv")

for file_name in "${myfiles[@]}"
do
        echo "removing first line of file $file_name"
        echo "first line is `head -1 $file_name`"
        echo "\n"
done

but it does not recognize the spaces for some reason, even though I enclosed it in double quotes "":

head: cannot open ‘file\\’ for reading: No such file or directory

How do I fix this?

Upvotes: 0

Views: 817

Answers (2)

l0b0
l0b0

Reputation: 58788

To expand on @JohnKugelman's answer:

  • Quoting takes a bit of getting used to in Bash. As a simple rule use single quotes for static strings with no special characters, double quotes for strings with variables, and $'' quoting for strings with special characters.
  • There's a separate quoting context inside every command substitution.
  • $() is a clearer way to establish a command substitution, because it can be nested much easier.

Consequently you'd typically write myfiles=('file with spaces.csv') and echo "first line is $(head -1 "$file_name")".

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361595

You need double quotes inside the backticks. The outer set isn't sufficient.

echo "first line is `head -1 "$file_name"`"

Also, do not put backslashes in the file name, since it's already quoted. Quotes or backslashes, but not both.

myfiles=("file with spaces.csv")
myfiles=(file\ with\ spaces.csv)

Upvotes: 4

Related Questions