Skip to main content
Became Hot Network Question
edited title
Link
ilkkachu
  • 147.9k
  • 16
  • 268
  • 441

How can I prevent bashto have Bash interpret output from splitting result of command substitution (eg file names with spaces)as quoted strings?

Source Link
Markus
  • 41
  • 1
  • 2

How can I prevent bash from splitting result of command substitution (eg file names with spaces)?

I have a program that gets the files selected in the graphical IU (in my case Finder in macOS). The output is something like

'/tmp/file number one.txt' '/tmp/file number two.txt'

Note the space char in the names, thus the file names are enclosed in ' (single straight ticks)

When using the output of that command in a command substitution in bash for e.g. the ls -l command everything is screwed up. For a test I put the above line into a simple one-liner text file and use it as command line substitution:

$ cat /tmp/files.txt
'/tmp/file number one.txt' '/tmp/file number two.txt'
$ ls -l $(</tmp/files.txt)
ls: "'/tmp/file: No such file or directory
ls: '/tmp/file: No such file or directory
ls: number: No such file or directory
ls: number: No such file or directory
ls: one.txt': No such file or directory
ls: two.txt'": No such file or directory

The same happens when I assign the file name string to a variable and use it

$ xxx="'/tmp/file number one.txt' '/tmp/file number two.txt'"
$ ls -l $xxx
ls: '/tmp/file: No such file or directory
ls: '/tmp/file: No such file or directory
ls: number: No such file or directory
ls: number: No such file or directory
ls: one.txt': No such file or directory
ls: two.txt': No such file or directory

Any idea how to solve this? Copying the escaped file names right onto the command line works as expected

$ ls -l '/tmp/file number one.txt' '/tmp/file number two.txt'
-rw-r--r--  1 tester  wheel     0B Jul 17 17:21:11 2021 /tmp/file number one.txt
-rw-r--r--  1 tester  wheel     0B Jul 17 17:21:16 2021 /tmp/file number two.txt

My ultimate goal is to use the current Finder selection (which I get through a compiled Applescript) to be available for use in bash. ls is just an example, I might want to use the list of files for tar, cp, mv or any other file handling stuff.