Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does /bin/bash -c differ from executing a command directly?

Tags:

bash

I'm curious why the commmand:

for f in `/bin/ls /mydir | sort | tail -n 10`; do echo $f; done;

Outputs the last ten files in /mydir, but

/bin/bash -c "for f in `/bin/ls /mydir | sort | tail -n 10`; do echo $f; done;"

Outputs "syntax error near unexpected token '[file in /mydir]'"

like image 732
JivanAmara Avatar asked Oct 02 '14 19:10

JivanAmara


People also ask

What is the difference between bash and command line?

CMD is the command line for Microsoft Windows operating system, with command-based features. Powershell is a task-based command-line interface, specifically designed for system admins and is based on the . Net Framework. Bash is a command-line and scripting language for most Unix/Linux-based operating systems.

What is the difference between bin bash and bash?

The answer to this question is, " -bash denotes a login shell and /bin/bash denotes a non-login shell." The answer to the other question is a list of differences between login shells and non-login shells.

What is the difference between executing a bash script vs sourcing it?

Sourcing a script will run the commands in the current shell process. Changes to the environment take effect in the current shell. Executing a script will run the commands in a new shell process.

What is the difference between bash and shell?

bash is a superset of sh. Shell is a command-line interface to run commands and shell scripts. Shells come in a variety of flavors, much as operating systems come in a variety of flavors. So, Shell is an interface between the user and the operating system, which helps the user to interact with the device.


1 Answers

You are using double-quotes, so the parent shell is interpolating backticks and variables before passing the argument to /bin/bash.

Thus, your /bin/bash is receiving the following arguments:

-c "for f in x
y
z
...
; do echo ; done;"

which is a syntax error.

To avoid this, use single quotes to pass your argument:

/bin/bash -c 'for f in `/bin/ls /mydir | sort | tail -n 10`; do echo $f; done;'
like image 178
nneonneo Avatar answered Oct 09 '22 03:10

nneonneo