0

If I run this: echo "After-u-math-how-however" | cut -f1,2 -d'-'

I get After-u

I want to set the output to a variable. But when I try to do this:

myVar=echo "After-u-math-how-however" | cut -f1,2 -d'-'

It fails with: bash: After-u-math-how-however: command not found

I am not sure how to fix this.

Rezzy
  • 111
  • 1
  • 2
  • 10
  • 1
    `myVar=$(something)` – Charles Duffy Mar 17 '23 at 19:20
  • That said, I'd generally suggest preferring parameter expansions over command substitutions; `fork()`ing off a subshell and then invoking an external command in it is a lot of overhead, relatively speaking. – Charles Duffy Mar 17 '23 at 19:21
  • How would you preferably do this command? – Rezzy Mar 17 '23 at 19:43
  • 1
    Depends on usage (and performance-vs-readability tradeoffs). If there's guaranteed to be at least two dashes, `IFS=- read -r a b _; myVar="$a-$b"` is a lot more efficient than the `cut` approach, despite being wordier. One can also use a regex: `[[ $string =~ ^([^-]*-[^-]*)- ]] && myVar=${BASH_REMATCH[1]}`, f/e, is another in-process approach. – Charles Duffy Mar 17 '23 at 19:52

0 Answers0