0

I'm trying to list all files in a folder and add them to a variable, separated by a semicolon.
Then I need to echo the variable in a file. This is my snippet

#!/bin/bash
SEP=";"
LIB="lib/"
DEP=""
ls -t1 target/lib/ | while read -r FILE
do
    DEP=$DEP$LIB$FILE$SEP
done
echo "$DEP"

The DEP variable is populated inside the while loop, if I echo from there I can see the correct result. Outside the loop the variable gets "cleared" and it echoes nothing. How do I keep the result? What am I doing wrong?

OsX 10.8.3 GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin12) Copyright (C) 2007 Free Software Foundation, Inc.

Alessandro Da Rugna
  • 4,571
  • 20
  • 40
  • 64

1 Answers1

4

The problem is not the while loop but the pipe. Everything after the | symbol is run in a subshell. To workaround the problem, use the process substitution:

while read -r FILE
# ...
done < <(ls -t1 target/lib/)
choroba
  • 231,213
  • 25
  • 204
  • 289