How do I store the output of a command in a variable? Here is what I am doing but nothing is being stored. It seems that pipes are the issue, but I don't know how to proceed debugging.
This works as expected:
$ var=$(printf "hello \n world") $ echo $var hello world
As does this:
$ printf "hello \n world" | wc -l 1
This does not:
$ var=$(printf "hello \n world" | wc -l) $ echo $var $ #previous command returns nothing
How do I get
var to store
1 in the third example?
Edit: Using bash, on Cygwin.
Edit 2: Running with
$ bash -x + [[ -z '' ]] + CYG_SYS_BASHRC=1 + [[ himxBH != *i* ]] + export 'EXECIGNORE=*.dll' + EXECIGNORE='*.dll' + PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$ ' + [[ himxBH != *i* ]] $ var=$(printf "hello \n world" | wc -l) + var= $ echo $var + echo
$ bash --version GNU bash, version 4.4.12(3)-release (x86_64-unknown-cygwin) Copyright (C) 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
set +o posix as suggested by @GeorgeVasiliou in a comment on my answer (now deleted by moderator, and copied below) does not change the output.
For some reason, the backtick syntax works for me, but not the
$ var=`printf "hello \n world" | wc -l` ++ printf 'hello \n world' ++ wc -l + var=1 $ echo $var + echo 1 1
If someone can explain why this happens, and more importantly how to fix it, that one should be the accepted answer.