I want to get command's original coloured output in a variable that i can print.

I have following script:

NC='\033[0m' # No Color

# Runing test cases
res=$(script -q /dev/null mocha $(find "tests/non-ui" -name "*.js")) #Command that runs test cases
[ $RESULT -ne 0 ] && echo -e "$res ${RED}Some TestCaes did not pass. Please check your code.${NC}" && exit 1
echo "All test cases passed.\n"
exit 0

It gives me following output:

Some TestCaes did not pass. Please check your code.:13:16)

where :13:16) part is some last characters of output of this command res=$(script -q /dev/null mocha $(find "tests/non-ui" -name "*.js")).

Running mocha $(find "tests/non-ui" -name "*.js") this command alone gives following output:

  All element creation test:
    1) Label

  0 passing (16ms)
  1 failing

  1) All element creation test: Label:

      AssertionError: false == true
      + expected - actual


      at Context.<anonymous> (tests/non-ui/sample-test.js:13:16)

How can i get whole output in a variable?

  • @Ravexina here is my problem statement. – chandil03 Jun 8 '17 at 11:36
  • I don't think your question has anything to do with coloured output. It is about capturing command output and put it in another command. To that end, it's not clear what you mean by 'whole output'. Is it the whole output from mocha $(find "tests/non-ui" -name "*.js")? – biocyberman Jun 8 '17 at 12:05
  • @biocyberman, you are right. I have another script(previous version of this script) where this command res=$(script -q /dev/null ./tests/ui-test) runs as i expect (./tests/ui-test file contains $( mocha $(find "tests/non-ui" -name "*.js")) ). This let me capture coloured output of a command written in tests/non-ui file. when i run res=$( mocha $(find "tests/non-ui" -name "*.js")) without script command. It gives me proper output but all formatting, indentation and colours are gone. – chandil03 Jun 8 '17 at 12:24
  • So later on i thought that combining these two script and mocha command will give me all output with colors but it gives only some characters of last line. – chandil03 Jun 8 '17 at 12:29

Add double quotes around your commands:

res="$(script -q /dev/null mocha $(find "tests/non-ui" -name "*.js"))"

echo "$res"

This will preserve the ANSI colors.

  • it is already in quotes "$res ${RED}Some TestCaes did not pass. Please check your code.${NC}". – chandil03 Jun 8 '17 at 12:58
  • 1
    Yes, but nor your command res="..." – Simon Sudler Jun 8 '17 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.