2

Can someone please explain this? I ran the commands as shown below

$ cat `bash`

$ ls

$ ctrl+D

and it's giving me some unexpected output on terminal.

NOTE: bash is in backquotes.

3
  • I'm curious. What were you trying to do? Commented Oct 18, 2012 at 7:28
  • This is quite offtopic here. SO is for programming questions. Commented Oct 18, 2012 at 9:30
  • @doubleDown i was just trying to understand the behaviour of bash shell when executed in backquotes . Commented Oct 18, 2012 at 11:24

1 Answer 1

6

Good question! The "unexpected output" is cat printing all of the files found by ls in the cwd. Detailed explanation follow:

On your first line:

$ cat `bash`

The bash part actually spawns a new shell from your original shell because bash is enclosed by backquotes (backquotes means to run the enclosed program in this context)

Then when you do:

$ ls

This is actually done in the newly spawned bash shell. It lists the directory of wherever the newly spawned bash shell is (should be the same as the original). This, in turn, in essence changes the cat command in the first step to

$ cat file_1 file_2 ... file_x

(basically all of the files in that directory returned by ls. However, you won't see these results yet because the output is waiting to be printed to the stdout of your original shell : cat is waiting to evaluate the stdout of your new bash shell.)

Lastly, when you do:

$ ctrl+D

It exits the new bash shell that you spawned from your original shell, and then cat outputs everything that got printed to stdout in the new shell (the search results from ls) into your old shell.

You can verify what I just said by:

$ cd ~/
$ mkdir temp_test_dir
$ cd temp_test_dir
$ echo "some text for file1" > file1
$ echo "other text for file2" > file2

Now run what you had in your question:

$ cat `bash`
$ ls
$ ctrl+D

And this is what you should see:

some text for file1
other text for file2

in some order, which is just cat outputting all of the files that were found by ls.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.