bash -c in linux? What does it actually do?
5 hours ago, shivajikobardan said:-c string — If the -c option is present, then commands are read from string.
This simply says, if you add a "-c" then the (first) string that follows the "-c" is interpreted as a command. So e.g.
bash -c "echo Hello"
will simply use the Bash shell to execute "echo Hello", causing Hello to be printed.
QuoteIf there are arguments after the string, they are assigned to the positional parameters, starting with $0.
This says how additional arguments are treated, meaning if you add more than one string after the "-c". Additional arguments are used to replace $0, $1, $2, … if they appear in the command.
For example
bash -c 'echo $0 $1' "Hello" "Test"
will run the command "echo $0 $1", replacing "$0" with "Hello" and replacing "$1" with "Test". That's all there is to it.
Note however, how I used single quotes around the first string, rather than double quotes. This prevents my native shell from replacing $0 and $1, and instead passes them to its command (i.e. bash) verbatim. If I use double quotes, this is printed instead (using zsh here):
zsh
This means my native shell replaces $0 and $1, causing "echo $0 $1" to turn into "echo zsh" before the string is passed to bash (via -c), which then executes "echo zsh", causing zsh to be printed.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now