0

Trying to compare two arrays and print the differences, and getting below error.

1.sh: line 9: syntax error near unexpected token `<'
1.sh: line 9: ` mapfile -t $1 < <(comm -23 <(echo "${a[*]}" | sort) <(echo "${b[*]}" | sort))'

If I run in command prompt its working fine and giving the results correctly. Whine i copy same code in 1.sh its throwing error

below is the code

a=(1 2 3 4 5 6 7 9 10 11 12)
b=(2 3 4 7 8 9 12)
function array_diff 
{
eval local a=\(\"\${$2[@]}\"\)
eval local b=\(\"\${$3[@]}\"\)
local IFS=$'\n'
mapfile -t $1 < <(comm -23 <(echo "${a[*]}" | sort) <(echo "${b[*]}" | sort))
}
array_diff RESULT a b
echo "${RESULT[@]}"

Output should be: 1 10 11 5 6

jww
  • 97,681
  • 90
  • 411
  • 885
user2601350
  • 207
  • 1
  • 3
  • 12
  • You are using *process substitution* with `< <(comm -23 <(echo "${a[*]}" | sort) <(echo "${b[*]}" | sort))` it includes a *process redirection* with `<(echo "${b[*]}" | sort)` .. why? `echo "${a[*]}"` will output on a single line which `sort` can't sort. (same for `echo "${b[*]}"`). Instead, e.g. `printf "%s\n" ${a[*]}` unquoted. – David C. Rankin Jun 19 '19 at 17:36
  • @DavidC.Rankin `comm` requires sorted input, so the script sorts it on the fly – that other guy Jun 19 '19 at 17:39
  • Ahh, yes, but `sort` can't sort all numbers on a single line. (or better `printf "%s\n" "${a[@]}"` – David C. Rankin Jun 19 '19 at 17:40
  • `local IFS=$'\n'` so it'll be on multiple lines – that other guy Jun 19 '19 at 18:00
  • any inputs please – user2601350 Jun 19 '19 at 18:03
  • Also see [How to use Shellcheck](http://github.com/koalaman/shellcheck), [How to debug a bash script?](http://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](http://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](http://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Jun 19 '19 at 18:41
  • @user2601350 You ran it with bash and saw that it worked, right? Are you asking for improvements now? – that other guy Jun 19 '19 at 18:43
  • It running fine when ran in bash, if I copy the same code in a script say 1.sh and run then its throwing error. – user2601350 Jun 20 '19 at 03:49
  • any inputs please – user2601350 Jun 20 '19 at 07:06

0 Answers0