Search code examples
bashcommand-substitution

why function variable not working in command substitution inside a function?


im running this in bashrc file

function simplefunc () {
    output=$(ls -1 "$HOME")
    linecount=$(${output} | wc -l)

    echo "${linecount}"
    echo "${output}"
}

getting this error

Desktop: command not found
0
Desktop
Documents
Downloads
Music
Pictures
Public
snap
SoftMaker
Templates
venv
Videos

i tried these too

putting "local" before variable or

# linecount=$(output | wc -l)
# echo "$(${output} | wc -l)"

Solution

  • I think you should change the third line to:

    linecount="$(echo "${output}" | wc -l)"
    # OR alternatvely:
    # linecount="$(wc -l < <(echo "$output"))"