Storing output of command in shell variable

  • I have an operation using cut that I would like to assign result to a variable

    var4=echo ztemp.xml |cut -f1 -d '.'

    I get the error:

    ztemp.xml is not a command

    The value of var4 never gets assigned; I'm trying to assign it the output of:

    echo ztemp.xml | cut -f1 -d '.'

    How can I do that?

  • Tok

    Tok Correct answer

    10 years ago

    You'll want to modify your assignment to read:

    var4="$(echo ztemp.xml | cut -f1 -d '.')"

    The $(…) construct is known as command susbtitution.

    @Vass: Better: `var4=$(echo ztemp.xml | cut -f1 -d '.')`. `$(…)` is mostly equivalent to ` \`…\` `, except that quoting inside backquotes is peculiar (and in particular nesting backquotes is not recommended), whereas quoting inside `$(…)` is unusually intuitive. Furthermore `$(…)` is more readable than ` \`…\` ` which is easily confused with `'…'` in many fonts. So if you're going to learn only one, learn `$(…)`.

    though the question explicitly states that the user wants to assign the output of a command to a variable, his intention in this case is very clearly to strip the file extension. since your answer has already been accepted, it would be most polite of you to update it to include tips from Dennis's answer below.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM