Quantcast
Channel: User Kamil Maciorowski - Super User
Viewing all articles
Browse latest Browse all 645

What is the second sh in `sh -c 'some shell code' sh`?

$
0
0

Question

I encountered the following snippet:

sh -c 'some shell code' sh …

(where denotes zero or more additional arguments).

I know the first sh is the command. I know sh -c is supposed to execute the provided shell code (i.e. some shell code). What is the purpose of the second sh?


Disclaimer

Similar or related question sometimes appears as a follow-up question after sh -c is properly used in an answer and the asker (or another user) wants to know in detail how the answer works. Or it may be a part of a bigger question of the type "what does this code do?". The purpose of the current question is to provide a canonical answer below.

The main question, similar or related questions covered here are:

  1. What is the second sh in sh -c 'some shell code' sh …?
  2. What is the second bash in bash -c 'some shell code' bash …?
  3. What is find-sh in find . -exec sh -c 'some shell code' find-sh {} \;?
  4. If some shell code was in a shell script and we called ./myscript foo …, then foo would be referred to as $1 inside the script. But sh -c 'some shell code' foo … (or bash -c …) refers to foo as $0. Why the discrepancy?
  5. What is wrong with using sh -c 'some shell code' foo … where foo is a "random" argument? In particular:

    • sh -c 'some shell code'"$variable"
    • sh -c 'some shell code'"$@"
    • find . -exec sh -c 'some shell code' {} \;
    • find . -exec sh -c 'some shell code' {} +

    I mean I can use $0 instead of $1 inside some shell code, it doesn't bother me. What bad can happen?

Some of the above may be considered duplicates (possibly cross-site duplicates) of existing questions (e.g. this one). Still I haven't found a question/answer that aims at explaining the issue to beginners who want to understand sh -c … and its allegedly useless extra argument observed in high quality answers. This question fills the gap.


Viewing all articles
Browse latest Browse all 645

Trending Articles