2

I'm trying to do a simple script, but I don't get how to pass a variable to the command that I need:

#!/bin/bash 
for i in 1 2 3
do
python -c 'print "a"*' $i
done
barbsan
  • 3,418
  • 11
  • 21
  • 28
neorus
  • 477
  • 1
  • 6
  • 19

3 Answers3

1

If you really want to go on with your solution using python -c, you would have to remove the space:

#!/bin/bash 
for i in 1 2 3
do
  python -c 'print "a"*'$i
done

But the approach suggested by Asmox makes more sense to me (and it has nothing to do with the question where you pipe the standard output to).

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • You absolutely *do not* have to remove the space. You just have to quote the whole argument. – Konrad Rudolph Feb 27 '19 at 10:28
  • This is **also** one possibility. I suggested to remove the space, because this requires the least changes to the original code, compared to `python -c "print 'a'* $i"`. – user1934428 Feb 28 '19 at 10:45
0

Maybe this topic will help: How do I run Python script using arguments in windows command line

Have you considered making a whole script? Like this one:

import sys

def f(a):
    print a

if __name__ == "__main__":
    a = int(sys.argv[1])
    f(a)

This example might seem overcomplicated, but I wanted to show you how to pass parameter from console to function

Asmoox
  • 592
  • 8
  • 23
  • i need this to pipe to another file, the whole line would be something like "python -c 'print "a"* $i ' | ./example " – neorus Feb 27 '19 at 08:52
0

I have tried the solution provided above and had to modify for python3+

due to lack of sufficient points I am not allowed to make a comment, thats why I posted my solution separately

#!/bin/bash
for i in {1..3}
do
  python -c "print ('a'* ${i})"
done

output~>
a
aa
aaa
Ahsan
  • 47
  • 5