Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exec line from file in bash

Tags:

bash

I'm trying to read commands from a text file and execute each line from a bash script.

#!/bin/bash
while read line;    do 
     $line
done < "commands.txt"

In some cases, if $line contains commands that are meant to run in background, eg command 2>&1 & they will not start in background, and will run in the current script context.

Any ideea why?

like image 923
Quamis Avatar asked Aug 28 '10 01:08

Quamis


People also ask

How do I read a file in bash?

Syntax: Read file line by line on a Bash Unix & Linux shell The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file. The -r option passed to read command prevents backslash escapes from being interpreted.


2 Answers

if all your commands are inside "commands.txt", essentially, you can call it a shell script. That's why you can either source it, or run it like normal, ie chmod u+x , then you can execute it using sh commands.txt

like image 145
ghostdog74 Avatar answered Nov 12 '22 18:11

ghostdog74


I don't have anything to add to ghostdog74's answer about the right way to do this, but I can cover why it's failing: The shell parses I/O redirections, backgrounding, and a bunch of other things before it does variable expansion, so by the time $line is replaced by command 2>&1 & it's too late to recognize 2>&1 and & as anything other than parameters to command.

You could improve this by using eval "$line" but even there you'll run into problems with multiline commands (e.g. while loops, if blocks, etc). The source and sh approaches don't have this problem.

like image 45
Gordon Davisson Avatar answered Nov 12 '22 17:11

Gordon Davisson