Search code examples
linuxshellbinaryfilescat

linux cat command with multiple binary files


I'm trying to get familiar with the cat command on the command shell in Linux. Running the following lines just produced an unexpected (at least by me) result:

cp /bin/ls file1
cat file1 file1 file1 > ls3
chmod u+x ls3
./ls3

I expected that the entire directory will be printed 3 times, but the result is that I get the entire directory printed only once. What's the reason for that? I thought there is no distinction between binary and text files in linux, and somehow the file is only written once?

I'd really like it if anyone could provide a useful resource/ guide to these basic commands and piping, since the basic ones never covered anything like what I just did.

Thanks.


Solution

  • Let me give you some background on why this might go wrong: in several programming languages, the whole program is embedded in a main() function, so ls might look like:

    main(){
      <show the listing of the current directory>
    }
    

    If you want to perform this three times, you might need:

    main(){
      <show the listing of the current directory>
      <show the listing of the current directory>
      <show the listing of the current directory>
    }
    

    But if you simply glue everything behind each other, you get:

    main(){
      <show the listing of the current directory>
    }
    main(){
      <show the listing of the current directory>
    }
    main(){
      <show the listing of the current directory>
    }
    

    And if you try to run this, the computer says "What is this? There is more than just one main() function? I don't know what to do, so I do nothing.

    So, as you see, glueing binary files in order to execute them multiple times is, however nice, a bad idea.