bash: passing paths with spaces as parameters?

fbrereto picture fbrereto · Sep 24, 2011 · Viewed 18.3k times · Source

I have a bash script that recieves a set of files from the user. These files are sometimes under directories with spaces in their names. Unfortunately unlike this question all the filenames are passed via the command line interface. Let's assume the paths are correctly quoted as they are passed in by the user, so spaces (save for quoted spaces) are delimiters between paths. How would I forward these parameters to a subroutine within my bash script in a way that preserves the quoted spaces?

Answer

Roland Illig picture Roland Illig · Sep 24, 2011
#! /bin/bash

for fname in "$@"; do
  process-one-file-at-a-time "$fname"
done

Note the excessive use of quotes. It's all necessary.

Passing all the arguments to another program is even simpler:

process-all-together "$@"

The tricky case is when you want to split the arguments in half. That requires a lot more code in a simple POSIX shell. But maybe the Bash has some special features.