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
$ 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
Edit 3:
$ 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>
Edit 4:
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 $(...)
syntax
$ 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.
bash -x
, repeat the exercise and paste whole output here. – jimmij May 12 '17 at 23:05bash --version
)? – jimmij May 12 '17 at 23:28$(…)
and backticks behave differently (outside of corner cases involving parsing what's inside, and your code is not a corner case), it would be a bug. A rather strange one. – Gilles 'SO- stop being evil' May 13 '17 at 22:22