jmcgrath207
jmcgrath207

Reputation: 2027

Creating a Array from new lines out in bash

I am trying to make a array/list from a bash output and then I want to for loop it. I keep on getting Syntax error: "(" unexpected (expecting "done"). If I had to put it in python term, I want to break the string up by \n and then for loop it.

  IFS=$'\n'
  DELETE = ($($MEGACOPY --dryrun --reload --download --local $LOCALDIR --remote $REMOTEDIR | sed 's|F '$LOCALDIR'|'$REMOTEDIR'|g'))
  unset IFS

  # And remove it

  for i in $DELETE; do
  $MEGARM $i
  done

Upvotes: 2

Views: 559

Answers (1)

John1024
John1024

Reputation: 113814

First, shell is not python. Spaces around equal signs don't work:

DELETE = ($($MEGACOPY --dryrun --reload --download --local $LOCALDIR --remote $REMOTEDIR | sed 's|F '$LOCALDIR'|'$REMOTEDIR'|g'))

When the shell sees the above, it interprets DELETE as a program name and = as its first argument. The error that you see is because the shell was unable to parse the second argument.

Replace the above with:

DELETE=($("$MEGACOPY" --dryrun --reload --download --local "$LOCALDIR" --remote "$REMOTEDIR" | sed 's|F '"$LOCALDIR"'|'"$REMOTEDIR"'|g'))

Second, regarding the for loop, DELETE is an array and arrays have special syntax:

for i in "${DELETE[@]}"; do
  "$MEGARM" "$i"
done

Notes:

  1. Unless you want word splitting and pathname expansion, all shell variables should be inside double-quotes.

  2. It is best practices to use lower or mixed case for variable names. The system uses all upper case variables for its name and you don't want to accidentally overwrite one of them.

Upvotes: 2

Related Questions