This question already has an answer here:

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

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?

marked as duplicate by G-Man, jimmij, ilkkachu bash Mar 13 at 12:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


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"

(removes the shortest trailing substring matching /*) and

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.