0

Let's say I have a text file that has three lines. Its called a

1
2
3

Is there a way to make this possible:

$ x='cat a | head -1'
Hunter.S.Thompson
  • 8,839
  • 7
  • 26
  • 41
dobby
  • 1
  • 1
    Do you really want to *name* the variable 1, or do you want to *assign the value* 1 to a variable named `x`? – steeldriver Jan 27 '18 at 04:18
  • Possible duplicate of [Why is using a shell loop to process text considered bad practice?](https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice) – Wildcard Jan 27 '18 at 04:23
  • You *can* do it, but the answer to "*should* you do this?" is a definite "no." However, look into **command substitution**, which is what you're looking for. (And it's a useful tool that has its place...this just isn't it.) – Wildcard Jan 27 '18 at 04:25
  • 1
    Very few questions are legitimately duplicates of that one, and this isn't one of them. – Michael Homer Jan 27 '18 at 04:43
  • 1
    This question has nothing to do with shell looops. It is just "how do I do [command substitution](https://en.wikipedia.org/wiki/Command_substitution)?". Answer is `x=$(cat a | head -1)` or, since the `cat` is unnecessary, `x=$(head -1 a)` – cas Jan 27 '18 at 05:04

1 Answers1

2

What you're trying to do is called command substitution, which puts the output of a command onto the command-line of another. e.g. to provide arguments for the other command, or to assign the output to a variable.

You almost had the right syntax. You need to use $() around your command. e.g.

x=$(cat a | head -1) or, since the cat is unnecessary, x=$(head -1 a)

backticks (`) can also be used but are considered obsolete, as they have a number of problems (including inability to nest them, and difficulty in distinguishing them from single-quotes).

cas
  • 1
  • 7
  • 119
  • 185