9

Does anyone know if there's a way to run automatically in shell a list of commands (from a text file)?

I need to run a lot of scripts (around 1000). The scripts are in python and take 2 arguments each (dir_#, and sample#)

The text file I've made looks like this...

     python /home/name/scripts/get_info.py dir_1 sample1
     python /home/name/scripts/get_info.py dir_2 sample2
     python /home/name/scripts/get_info.py dir_3 sample3
     python /home/name/scripts/get_info.py dir_4 sample4
     ...

So, I would expect that passing this text file as argument to a command in terminal, could do the job automatically...

Thanks in advance,

peixe

UmNyobe
  • 21,924
  • 8
  • 55
  • 89
peixe
  • 1,165
  • 3
  • 13
  • 29

4 Answers4

26

That's called a "shell script."

Add this to the top of your file:

#!/bin/sh

Then execute this command:

chmod +x filename

Then execute it like a program:

./filename

Alternately, you can execute the shell directly, telling it to execute the commands in your file:

sh -e filename
Flimzy
  • 68,325
  • 15
  • 126
  • 165
7

Also, you can run a shell file by:

source filename
m00am
  • 5,404
  • 11
  • 53
  • 64
Noon
  • 83
  • 1
  • 6
  • i do not get, why this got a downvote... https://stackoverflow.com/questions/13786499/what-is-the-difference-between-sh-and-source both kind of fits the need, especially if you need to define some variables for the session as well – Vairis Feb 12 '18 at 21:45
6

Either make the file executable:

chmod u+x thefile
./thefile

or run it as an argument of sh:

sh thefile
  • Simply making it executable won't work, unless the first line includes #!/bin/sh – Flimzy Jul 01 '11 at 09:23
  • That is not true, not with bash at least. –  Jul 01 '11 at 09:24
  • Perhaps not with bash, but I don't think we can assume everyone is using bash--your own answer doesn't assume that with "sh thefile" :) – Flimzy Jul 01 '11 at 09:25
  • AFAIK, scripts only need this directive to ensure a specific shell is used and is by no mean mandatory. –  Jul 01 '11 at 09:32
2

You can write a shell script:

#! /bin/sh

python /home/name/scripts/get_info.py dir_1 sample1
python /home/name/scripts/get_info.py dir_2 sample2
python /home/name/scripts/get_info.py dir_3 sample3
python /home/name/scripts/get_info.py dir_4 sample4
...
Giann
  • 3,054
  • 3
  • 22
  • 33