1

I am trying to set the variable service to be the value of

var1=first/second
echo $var1 | cut -d '/' -f 1
var2=$var1 | cut -d '/' -f 1"
echo $var2

The result of echo $var1 | cut -d '/' -f 1 is "first" which is correct. However, I haven't been able to set the result of this to another variable. In the case above, var2 is empty.

What would the correct syntax for line 3 be so that the part of the string before the \ is returned as the value of var2?

fuzzi
  • 13
  • 1
  • 6
  • 1
    See also [Storing output of command in shell variable](https://unix.stackexchange.com/q/4569/80216), [Calculate variable and output it to another variable](https://unix.stackexchange.com/q/50215/80216), [Bash: Assign output of pipe to a variable](https://unix.stackexchange.com/q/338000/80216), [setting output of a command to a variable](https://unix.stackexchange.com/q/122014/80216), and more. – G-Man Says 'Reinstate Monica' Mar 12 '19 at 23:32

1 Answers1

2

You could use command substitution

var2=$(echo "$var1" | cut -d '/' -f 1)

However in this case it would be better to use the shell's parameter substitution directly:

$ var2=${var1%/*}
$ echo "$var2"
first

(removes the shortest trailing substring matching /*) and

$ var3=${var1#*/}
$ echo "$var3"
second

(removes the shortest leading substring matching */) should you need it as well.

steeldriver
  • 78,509
  • 12
  • 109
  • 152