0

I have a bash script with a for cycle in it called test.sh:

#!/bin/sh
echo -n > "/path/output.txt"
for i  in {1..10}
do 
echo "Test" >> "/path/output.txt"
done

I would like to run it in background while the instruction of the Python script are performed. I am using Python subprocess:

import subprocess
subprocess.Popen('test.sh')

I can't get any output or the output is written in "output.txt" only once.

3
  • Your she-bang is wrong, it should have be #!/bin/sh Commented Jan 5, 2017 at 18:28
  • You probably also want echo -n "" or something, unless you want a literal -n written to that file. If you just want to create the file, try touch. Commented Jan 5, 2017 at 19:17
  • @meatspace if I use touch I can't overwrite the file if it is already exist Commented Jan 9, 2017 at 9:32

2 Answers 2

2

Generally, don't use brace expansions with loops. The shell has to expand the entire expression before you can iterate over it. Either use a C-style for loop (in shells like bash that support it):

for ((i=1; i<=10; i++)); do
    ...
done

or use a while loop (in any POSIX-compatible shell):

i=1
while [ "$i" -le 10 ]; do
    ...
    i=$((i+1))
done
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry: while [ $i -le 10] do i=$(( $i + 1)). Ok, I guess they are both rigtht
The arguments can only be integers in an arithmetic context, so identifiers are automatically dereferenced.
0
for i in {1..10}

is not valid syntax for sh. You tagged you question with Bash, so replace the first line with

#!/bin/bash

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.