What have I done wrong?
In no particular order,
- You didn't have
#!/bin/bash
or equivalent as the first line.
- You don't seem to have posted the actual script that's failing. (What you have here is syntactically correct.)
- You haven't double-quoted your variables,
"$n"
instead of $n
.
- You're using obsolete backticks for evaluation instead of
$( ...)
.
- You haven't tested your code in https://shellcheck.net/
- You haven't indented your code blocks to make them easier to read.
- If you are adding elements to an array, use
array+=($num)
. What you have in your code is string concatenation to the last element.
- In the (new) first block you assign to elements (0 .. n-1) but you later use elements (1 .. n).
- In the (new) second block you are comparing the indices for inequality rather than the array elements. Did you mean to compare
"${array[$i]}" -ne "${array[$j]}"
(or, for the (( ... ))
construct, array[i] != array[j]
)?
(I should probably point out that some of these are good practice rather then essential coding rules.)
Here is your code with my suggestions applied:
#!/bin/bash
read -p 'Number of elements: ' n
array=(0) # We don't use element zero
for i in $(seq "$n")
do
read -p 'Element: ' num
array+=($num)
done
for i in $(seq "$n")
do
for j in $(seq "$n")
do
# Compare the array elements rather than the indices
# Is this what you intended?
if (( array[i] != array[j] ))
then
echo "${array[$i]} ${array[$j]}"
fi
done
done
n
should be set,$(...)
is nicer than backticks and it might be prudent to quote the variables.if
. That would make it a different word, not recognized as theif
keyword. And thenthen
would be misplaced. (it would beif_[
, with_
representing the nbsp)array+=$num
probably doesn't do what you want, you may wantarray+=($num)
instead