0

I have the following bit of code in a bash script I've created. When I run it from a directory with no spaces in the path it works as expected, however if I run from a directory with spaces it fails. I'm pretty sure I need to escape it somehow, but nothing I've tried seems to work.

for file in `pwd`/*
do 
    echo file:$file
done

By 'fails' I mean that if I run the command from the path "~/dir 1/ test" it would echo the following:

file: ~/dir
file: 1/
file: test

I'd expect it to list the files in the directory (which it does if there's no spaces in the current directory):

file: file 1
file: file 2
file: file 3

Note this is only an issue if the current directory has spaces in, files with spaces in are processed fine.

I've read several similar examples on here such as Why does my shell script choke on whitespace or other special characters? and Looping through files with spaces in the names? but I can't see how (if they are relevant) they apply to my specific example.

Al_
  • 101
  • 4
  • what does `it fails` mean? – jsotola Jan 12 '20 at 23:10
  • 5
    Does this answer your question? [Looping through files with spaces in the names?](https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names) – kaylum Jan 12 '20 at 23:11
  • 1
    Does this answer your question? [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters) – Paulo Tomé Jan 12 '20 at 23:12
  • @jsotola I've edit the question so the formatting works – Al_ Jan 12 '20 at 23:13
  • kaylum & Paulo Tomé I've read both of those, and if they do apply I don't understand how to apply them to the specific example above – Al_ Jan 12 '20 at 23:16
  • 1
    put that info into the question above .... questions should have the following format `this is what i am trying to do ... this is what i expect to happen ... this is what actually happens .... this is my question` – jsotola Jan 12 '20 at 23:17
  • the link provided by @PauloTomé says to use double quotes around variables ... try `echo file:"$file"` – jsotola Jan 12 '20 at 23:22
  • I tried that, but it doesn't work. I believe the problem is with the line containing "for file in `pwd`/* as the array that line generates is what is at fault – Al_ Jan 12 '20 at 23:26
  • 2
    Suggestion: `for file in "$(pwd)"/* do echo file:"$file" done` – Paulo Tomé Jan 12 '20 at 23:29
  • 2
    @paull Tomé Thanks that was the answer – Al_ Jan 12 '20 at 23:33
  • 3
    Suggestion: Use a linter to check your scripts, for instance: [ShellCheck](https://www.shellcheck.net/). – Paulo Tomé Jan 12 '20 at 23:37

1 Answers1

0

Thanks to Paulo Tomé I needed to change it to the following:

for file in "$(pwd)"/* 
do 
    echo file:"$file" 
done
Al_
  • 101
  • 4