Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between "sh -c 'some comand'" and directly run some command

Tags:

shell

sh

let's say echo command, we can run that command by two ways:

# by 1
echo 'hello'
# or by 2
sh -c "echo 'hello'"

Is there any difference between the two ways? By the way, I can see the way 2 is very popular in yaml config files.

- name: init-mydb
  image: busybox:1.28
  command: ['sh', '-c', "sleep 2; done"]
like image 724
fish Avatar asked Jan 27 '26 09:01

fish


2 Answers

The first way calls an inherited command interpreter, eg from a terminal running /bin/bash ; the second way exec sh (aka Bourne Shell) as the interpreter and instruct him ( -c ) to do something.

sh, ksh, csh, bash are all shell interpreters. They provide some features that are not always compatible between them. So, if you don't know the environment where your program will run, the best is to specify the interpreter you want, which is less error prone.

like image 78
Valery S. Avatar answered Jan 29 '26 06:01

Valery S.


This is a single command:

foo 1 2 3

So is this

sh -c 'foo 1 2 3'

This is not a single command (but rather a pair of commands separated by a ;)

foo; bar

but this is

sh -c "foo; bar"

This does not specify a command using the name of a executable file

for x in 1 2 3; do echo "$x"; done

but this does

sh -c 'for x in 1 2 3; do echo "$x"; done'

sh -c is basically way to specify an arbitrary shell script as a single argument to a command that can be executed from a file.

like image 37
chepner Avatar answered Jan 29 '26 04:01

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!