Nashed
Nashed

Reputation: 9

Creating an array of files in a subfolder

I'm trying to write a bash script for a homework question where I need to access some files in a source folder, remove all comments from them and send the uncommented files (or a copy) to a destination folder, here's my current attempt:

#!/bin/bash
destination="$1"
source="$2"
mkdir "$destination"
files=(${$("$source"/*)})
for file in "${files[@]}" 
do  
    grep -E -v "^[[:space:]]*[//]" "$file">> "/$destination/$file"
done

The problem seems to be I'm not creating the array elements correctly, I want the array to contain the names of the files in the source folder, can anyone direct me to the correct way of doing that (preferably without solving the whole exercise as it is homework after all)/

Upvotes: 1

Views: 50

Answers (2)

chepner
chepner

Reputation: 531490

You actually don't need the array at all, and for a large number of matching files it is more efficient as well to iterate over the pattern directly.

for file in "$source"/*; do

Upvotes: 2

codeforester
codeforester

Reputation: 43019

Change this

files=(${$("$source"/*)})

to

files=("$source"/*) # grab name of all files under $source dir and store it in array

Upvotes: 4

Related Questions