4

I have a variable called var that stores the list of files inside a directory. I loop through all the files and if I find a directory I output "Directory" to the screen. code below:

var=$(ls dir)

for file in $var; do
    if [ -d $dir/$file ]; then
        echo "Directory"
    fi
done

I have 2 questions:

1st- I am doing this inside a function and I want the $file variable to stay local so when my function ends I don't get access to it. How can I set that variable local? I cant do for local file in $var; and I cant declare $file before the loop.

2nd- My loop doesnt work when $(ls dir) contains a file that has a space inside the name. For example if $dir has 3 files, file1 file 2 and file3, $var would only hold file1 and file3 as real files but file 2 would not work because it would separate it into file and 2. How can I fix the problem of the files that have space in their names?

  • 2
    for the space, put double quotes around "$file". for more complex situations you might have to use $"$file". – Frank Thomas Dec 29 '15 at 16:00
  • I tried that but it didn't work because I am already getting the space from $(ls dir), so when I initialize my variable file I am already taking the space into consideration. – Fxbaez Dec 29 '15 at 16:04
  • 3
    Try ls -Q dir. this will put quotes around each file name. This issue is part of why it is recommended that people avoid parsing ls output, and instead use find. – Frank Thomas Dec 29 '15 at 16:10
3

For making $file local: you can use local file before assigning to it.

For files with spaces: don't parse ls, use a wildcard, and use double-quotes around variable references:

local file
for file in "$dir"/*; do  # Note that $file will contain $dir as well as the filename
    if [ -d "$file" ]; then
        echo "Directory: $file"
    fi
done

If you want to store the file names before starting the loop, use an array instead of a plain variable:

local -a filelist
filelist=("$dir"/*)
local file
for file in "${filelist[@]}"; do
    ...

See BashFAQ #20: "How can I find and safely handle file names containing newlines, spaces or both?" for more complex examples and more tricks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.