1

I'm trying to use an IF/ELSE statement inside a FOR loops to generate two output files: count1 with numbers 1-5; count2 with numbers 6-10

I am trying

for i in {1..10}
do
        if [ $i -le 5 ]
        then
                echo $i > count1.out
        else
                echo $i > count2.out
        fi
done

but count1 only has "5" in it and count2 shows "10"

How can I fix this?

1
  • 3
    Use >> instead of >. >> appends text, but > overwrites whatever is in the file. Commented Feb 25, 2016 at 3:26

2 Answers 2

1

You are using the truncate-redirect operator, >.

You likely intended to use the append-redirect operator, >>.

Consider reading up on BASh I/O redirection in general. It will help you a lot with understanding shell scripts.

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

Comments

1

Using > to redirect to a file replaces the whole content of the file. What you actually want to do is append to the file, which you can do with >> like so:

echo "hello " > somefile.out # replace the contents of whatever is in somefile.out
echo "world!" >> somefile.out # append more stuff to somefile.out

More info here: https://www.gnu.org/software/bash/manual/html_node/Redirections.html

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.