I am trying to execute specific line of text file in bash. I was wondering is it possible to do that without copying that line in a new file and executing it?
|
Building on @kev's answer (without piping to a new
|
@ormaaj: I agree with you in discouraging such a concept. On the other hand it comes handy when following instructions from a simple diary (log) file. – fheub Jul 13 '12 at 9:49 |
|||
|
@fheub: This isn't a good answer because the argument list is built by word-splitting, with pathname expansion enabled. This will fail in all but simple cases. Always quote command substitutions. kev's answer is ok. Mine works in either a child process or the current environment because of the eval (and uses properly escaped input). If you have GNU sed available, a shell command can be executed in pure sed using the e function: sed -n $'3{e\np;q}' file – ormaaj Jul 13 '12 at 10:15 |
||
|
I think you should pipe to bash as Vladimir wants to execute the line. – Bernhard Jul 13 '12 at 7:27 |
|
If you are talking about a shell script, you could do that like in this example:
Another example includes capturing the output for further processing:
In the second example, the variable |
|||
|
|
|
Probably not quite what you want, but could be useful to mention:
This reads each line of the script into your history list, from which you can execute any line using A few failed attempts at reading in just the line you want to execute:
|
||||
|
|
|
You could but probably shouldn't. Create a library containing functions and source it. This is a very unusual requirement. Bash has actual means of control flow - there's no need to grab strings of code out of files to execute. This can be dangerous. Here's a "toy" example, not for production use...
Late edit: Note the comment regarding a bug in |
||||
|
|