Consider the following shell script


The ls does not not give any shell text output. Now, how do we get output text on screen while the command is being executed?

I can print the value of val to get the output, but using echo is not the point. So, using the following line is not the case

echo $val

So, in nutshell, how do I get the output of current command being executed in shell simultaneous as if you were executed the command by itself?

  • 3
    Your assignment is wrong, it would be val="$(ls)" and then echo $val Jul 8, 2017 at 10:03

2 Answers 2


You can get the shell to echo everything it is doing, by running the following command:

sh -x yourscript

Or you can add this as the first command in the script:

set -x

It can get a bit too verbose, though. It's OK for debugging, but if you want selective output it would be best to do it yourself with carefully places echo commands.

  • 3
    That is not going to show the output of commands - it will only show which commands are being run.
    – l0b0
    Jul 8, 2017 at 8:39
  • It showed the output of ls in the original questioner's example. I tried it. Which is what he was asking about. Presumably because the output of ls actually forms part of the subsequent command.
    – Bob Eager
    Jul 8, 2017 at 13:39
  • how come this is accepted as the answer.it showed me the commands ..not the output Sep 5, 2020 at 17:58

You can tee commands to send a copy of standard output to a file, and you can use the current terminal as that output file. As you can see in the following, it will print twice if you don't use the output for anything, and once if standard output is swallowed by doing something to it:

$ echo foo | tee -a "$(tty)"
$ echo foo | tee -a "$(tty)" | grep bar
  • could someone clarify what /dev/tty is here?
    – Arthur Yip
    Mar 24, 2021 at 15:31
  • As mentioned, it refers to the current terminal. See man tty.
    – l0b0
    Mar 24, 2021 at 18:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .