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:
- What is the second
sh
insh -c 'some shell code' sh …
? - What is the second
bash
inbash -c 'some shell code' bash …
? - What is
find-sh
infind . -exec sh -c 'some shell code' find-sh {} \;
? - If
some shell code
was in a shell script and we called./myscript foo …
, thenfoo
would be referred to as$1
inside the script. Butsh -c 'some shell code' foo …
(orbash -c …
) refers tofoo
as$0
. Why the discrepancy? What is wrong with using
sh -c 'some shell code' foo …
wherefoo
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
insidesome 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.