-2

I am trying to make sh script which uses 'sed' to make bubblesort algorithm

I am strugling, how to make for loop

for n in $1
do
   echo $n
done

How can I change body of the for loop to make just n-1 cycles? I tried this $1-1 but it doesn't work. It will print part of the string and - 1.

closed as unclear what you're asking by Michael Homer, don_crissti, Rui F Ribeiro, Anthony Geoghegan, DarkHeart Apr 24 '17 at 5:28

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • show $1 value – RomanPerekhrest Apr 22 '17 at 15:26
  • "1 2 3 4 12 56" – Muffy Apr 22 '17 at 15:27
  • 2
    Which shell are you using? if it supports arrays - use one e.g. (bash) list=(1 2 3 4 12 56) ; for ((i=0; i<${#list[@]}-1; i++)); do echo "${list[i]}"; done – steeldriver Apr 22 '17 at 16:01
  • You should edit your question to add important details rather than post them in comments which may not be read. See How to Ask. – Anthony Geoghegan Apr 23 '17 at 23:03
1

n-1 cycles means that the last item shouldn't be considered.

Use the following approach(assuming that your input argument will always be a string of space-delimited substrings):

s=$1

for n in ${s:0:-2}
do 
    echo $n 
done

${s:0:-2} - slice of items containing all items except the last one

    ^  ^
    |  | 
  from to
-1

Use for i in "$@" ; do echo $i ; done

You don't need to quote $1, it's not necessary.

Edit: I misunderstood. If you wish to print $1-1, echo $(( $i-1 )) If you are trying to iterate i-1 times, use a modification of this:

for ((i=1; i<=3; i++))
{
  echo $x
}

Please post your 'bubblesort' script in full, or clarify your question.

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