0

I am trying to get all possible combinations of a of strings within a certain command, except when the strings are the same. I simplified what I'm trying to do and how I tried to do it as follows:

for i in a b c
do
for p in a b c
do
if [ $i -ne $p ]
then
echo "$i and $p"
fi
done
done

The output I expect is:

a b
a c
b a
b c
c a
c b

But it does not seem to work.. any ideas what's wrong with my nested for loops?

1
  • This might help: help test Commented Apr 9, 2017 at 17:48

1 Answer 1

3

Replace :

if [ $i -ne $p ]

With :

if [ "$i" != "$p" ]

The -ne operator requires integers. The != operator works on strings.

You should usually double quote strings in tests, unless you are really, really sure they cannot contain more than one word (as seen by the shell following word splitting).

If using Bash, you can use the Bash-specific [[ ]] test construct.

if [[ $i != "$p" ]]

Double quotes are generally not needed in this type of test, as instead of being a command, it is special shell syntax and is not exposed to word splitting. However, the right-hand part of the comparison should be quoted to disable pattern matching, unless you are absolutely sure no string that will ever be used there could trigger pattern matching.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.