Bash – Assign variable using multiple lines

assignmentbashnewlines

I have a function

f(){
    echo 777
}

and a variable to which I assign the "return value" of the function.

x=$(f)

Very concise! However, in my real code, the variable and function names are quite a bit longer and the function also eats positional arguments, so that concise line above, gets very long. Since I like to keep things tidy, I would like to break the code above in two lines.

x=\
$(f)

Still works! But: keeping things tidy also means respecting the indentation, so that gives something like

if foo
    x=\
    $(f)
fi

which does not work anymore due to whitespaces! Is there a good workaround for this?

Best Answer

You can store the value in $_, which is set to the last argument:

if foo; then
    : "$(f)"
    x=$_
fi

Or can use a subshell to eat the indent:

if foo; then
    x=$(
    )$(f)
fi
Related Question