I have a text file that contains bash commands for fetching some data from a database. Each command is separated with a newline. See an example below: (the commands could also have been "ls -l", "cat whatever.txt", etc.)

prefetch SRR403012
fastq-dump --fasta 0 SRR403012
my_cpp_program.out SRR403012

How do I create a bash script that executes all these commands? I want something that executes the command in sequential order. However! It's important to note that the commands will take time before termination, because of the enormous files I am fetching. Thus, the for loop should also wait until the execution has finished.



        execute $LINE
  • Is there a reason why you don't run the file with bash ? Mar 18, 2021 at 10:00
  • because I'm a noob and don't know how to use bash for it.. Honest answer Mar 18, 2021 at 10:02
  • A bash script is a list of commands. Mar 18, 2021 at 10:06
  • sourcing the file should do the same result. source ./my_command.txt or . ./my_command.txt aka dotting in the file. See help source or help .
    – Jetchisel
    Mar 18, 2021 at 13:09

2 Answers 2


Your list of commands is effectively a shell script, even without a shebang (the #!/bin/bash line at the top). You can specify it as an argument to the shell, and the shell will execute it, one line at a time, waiting for the execution to complete:

bash my_commands.txt

or, if your commands don’t actually need bash,

sh my_commands.txt
  • source would be approriate here. Mar 18, 2021 at 17:51
  • 2
    @glennjackman that makes a number of assumptions about the commands to be run though; source my_commands.txt is more likely to produce surprising results for the user than bash my_commands.txt (e.g. if my_commands.txt includes exit, or PATH=... etc.). Mar 18, 2021 at 18:07

bash scripts are

  1. executed in order of lines
  2. except for if you make it not to

The hashbang #!/bin/bash is only necessary if you want to make the file itself an executable and to show which command is meant to interpret the command lines following thereafter.

So all you would need to do is bash your-command-file

Check this "command file". Save it as commands1 and run bash commands1

echo -n "Hi, "
sleep 1
echo -n "how "
sleep 1
echo -n "are "
sleep 1
echo "you?"

And compare to this one (commands2):

echo -n "Hi, " &
sleep 1 &
echo -n "how " &
sleep 1 &
echo -n "are " &
sleep 1 &
echo "you?"

As you can see, in the latter case, the commands are executed more or less in parallel by sending making the commands background processes 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.