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?

1

1 Answer 1

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.

Not the answer you're looking for? Browse other questions tagged .