0

Bash version: GNU bash, version 4.4.23(1)-release (x86_64-cros-linux-gnu) command:

file=fileName; line=3;

head -$line $file | tail -1;

In my usage, the above line is constructed by a bash script. How can I put the above command in a bash variable, and then execute it?

cmd='head -$line $file | tail -1;'

To run, $cmd in back quotes does not work.

Thank you.

Barmar
  • 741,623
  • 53
  • 500
  • 612
CqN
  • 139
  • 1
  • 8
  • Please take a look at [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting). – Cyrus Feb 22 '22 at 19:57
  • 2
    If you wish to evaluate the string `"$cmd"`, you can tell bash to do so with `eval`. eg. `eval "$cmd"`. There are many pitfalls. – William Pursell Feb 22 '22 at 20:04
  • 1
    [I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050) – chepner Feb 22 '22 at 20:11
  • @viv3k, `eval $cmd` is _exceptionally_ buggy. If someone really wants to use `eval` and accept its pitfalls (which are serious, and on account of which one should use the approaches described in BashFAQ #50 instead), they should use `eval "$cmd"`, **with the quotes**. Without the quotes, you're string-splitting your variable's contents, expanding each word resulting from the splitting as a glob, _concatenating all the results of those operations together into a single string_, and running that _new_ string through the parser as code. – Charles Duffy Feb 22 '22 at 20:52
  • ...so if you have `cmd='ls *.txt'`, and you run `eval $cmd` in a directory that contains a file named `$(rm -rf ~).txt`, someone is going to have a _very_ bad day. (There are plenty of accidental failure cases as well as the malicious ones, but count that as a particularly egregious example) – Charles Duffy Feb 22 '22 at 20:56
  • `the above line is constructed by a bash script` Why are you "constructing line to be executed" with a bash script? What do you mean by that? – KamilCuk Feb 22 '22 at 23:05

0 Answers0