1

I have the following code:

entries=("Wet\ Picnic" "Arizona\ Jones" "Bikeboy")
for arg in "${entries[@]}"; do ls -lh $arg.* ; done

It gives me 4 errors and 1 success. I'd really like it to give me 3 successes.

How do I handle the fact that the arguments to ls contain spaces (I've obviously tried escaping them as that's how it is currently), but to no avail.

The console output is currently.

ls: Wet: No such file or directory
ls: Picnic: No such file or directory
ls: Arizona: No such file or directory
ls: Jones: No such file or directory
-rw-r--r-- 1 root root 0 Jun 27 17:55 Bikeboy.png

SO it's clearly splitting on the space. Even though it's escaped.

1 Answer 1

7

You're escaping in the wrong spot. Try this example:

entries=("Wet Picnic" "Arizona Jones" "Bikeboy")
for arg in "${entries[@]}"; do ls -lh "$arg".* ; done

It should work fine. Here's a complete example, including the "People's Stage" you mentioned in the comments:

$ ls
Arizona Jones.png   People's Stage.png  example*
Bikeboy.png         Wet Picnic.png
$ cat example 
#!/bin/bash

entries=("Wet Picnic" "Arizona Jones" "Bikeboy" "People's Stage")
for arg in "${entries[@]}"; do ls -lh "$arg".* ; done
$ ./example 
-rw-r--r--  1 carl  staff     0B Jun 27 10:00 Wet Picnic.png
-rw-r--r--  1 carl  staff     0B Jun 27 10:00 Arizona Jones.png
-rw-r--r--  1 carl  staff     0B Jun 27 10:01 Bikeboy.png
-rw-r--r--  1 carl  staff     0B Jun 27 10:11 People's Stage.png
Sign up to request clarification or add additional context in comments.

2 Comments

However... If I had entries=("Wet Picnic" "Arizona Jones" "Bikeboy" "People's Stage") - how would I escape the apostrophe?
@MattFellows - did you try it? It works exactly the same, no changes required.

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.