I want to use Shell to run my Python script and use the variable from for loop to name my output file

for i in 1 2 3 4 5
setsid python main.py 1>data/$i$_logfile.txt 2>&1

But I got 1.txt not 1_logfile.txt. How can I do it successfully?


Because _ is a valid character for a variable name, you need to use the ${varname} syntax to let the shell know the end of the variable name. Otherwise, you have $i and $_logfile as variables, but the latter is empty.

The syntax $i$ does not exist.


setsid python main.py 1>data/${i}_logfile.txt 2>&1

Note that $variable is actually a simplified form of ${variable}. In contexts where the $variable syntax causes an error, the longer form may work. (via)

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.