Home > Blockchain >  How to run multiple bash command corresponding to each line input from a file?
How to run multiple bash command corresponding to each line input from a file?

Time:10-26

I want to run multiple commands in bash whose arguments are each line in a file

e.g.

$ cat argsFile.txt
argtype1
argtype2
argtype3

And I want to run 3 bash commands corresponding to each line in the file

$ python myscript.py argtype1
$ python myscript.py argtype2
$ python myscript.py argtype3

How do I do this in 1-2 lines in bash?

CodePudding user response:

I think this can be sufficiently accomplished by:

while read -r args; do <command> "${args}"; done < inputfile

So it becomes:

while read -r args; do python myscript.py "${args}"; done < argsFile.txt

You can write an echo right before the command to ensure it's going to run what you want:

while read -r args; do echo python myscript.py "${args}"; done < argsFile.txt
python myscript.py argtype1
python myscript.py argtype2
python myscript.py argtype3

CodePudding user response:

It is a single liner using xargs to run a command line using each line of input file:

xargs -n 1 python myscript.py < argsFile.txt

Note that if input file is very big and you want to run these commands in parallel then you can add -P 0 option of xargs:

xargs -P 0 -n 1 python myscript.py < argsFile.txt
  • Related