user3263650 user3263650 - 3 months ago 11
Linux Question

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

Answer

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.

Comments