0

I've wriiten a program in unix shell script to sort an array of integers. But I'm getting an error in the LINE 11, The Line is,

while [ $d -gt 0 && ${a[$(d-1)]} -gt ${a[$d]} ]

The error is like insertionsort.sh: line 11: [: missing]'` .What I'm doing wrong?

2

You need to split that test command (and quote your expansions if you are using a POSIX-compliant shell):

[ "$d" -gt 0 ] && [ "${a[d-1]}" -gt "${a[d]}" ]
  • 1
    Note that the POSIX shell specification doesn't specify arrays. That code is for ksh or bash, all other shells have their array indices start at 1, not 0. – Stéphane Chazelas Mar 28 '18 at 6:09
1

Since that's ksh syntax (also supported by bash and zsh -o ksharrays) because of those arrays whose indices start at 0 (as opposed to 1 in all other shells), you might as well use the ksh ((...)) arithmetic evaluation operator here:

while ((d > 0 && a[d-1] > a[d]))

(others have already explained the problems in your code).

Note that zsh has builtin support for sorting arrays of decimal integers numerically:

$ a=(10 6 2)
$ echo ${(n)a}
2 6 10

ksh can sort arrays, but only lexically AFAIK:

$ a=(10 2 6)
$ set -sA b -- "${a[@]}"
$ echo "${b[@]}"
10 2 6
1

There are two errors in the code:

  1. When using [ ... ] for tests, separate the tests in multiple [ ... ] with logic operators in-between:

    while [ expression ] && [ expression ]; do
    

    You may use your way of constructing the test if you're using bash and its [[ ... ]]:

    while [[ expression && expression ]]; do
    

    ... but it will probably still be more readable if it's split up as

    while [[ expression ]] && [[ expression ]]; do
    

    at least for longer or more expressions. For arithmetic-only test, you may use (( ... )) in bash and other shells that supports it, e.g. (( arithmetic expression )) && (( arithmetic expression )). In (( ... )) you should also use <, > etc. in place of -lt, -gt etc.

  2. Assuming you are using bash arrays, the index into the array is evaluated in an arithmetic context. This means that ${a[$d]} may be written ${a[d]}. More importantly, ${a[$(d-1)]} is probably an error since it would try to run a command called d-1. This should probably be ${a[d - 1]}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.