-1

When I use docker, I want to do some operations in the container for host by docker exec, I meet the problem.

I want do something like this but with error:

# in host
docker exec test-container bash -c "for i in `ls /folder-in-docker`; do someoperationon($i); done"

I simplify the problem reproduced with a command:

# host environment
docker exec test-container bash -c "for i in `ls /`; do echo $i; done"
>! bash: -c: line 2: syntax error near unexpected token `boot'
>! bash: -c: line 2: `boot

I want the code "for i in ls /; do echo $i; done" executed in the container, but ls / is done in the host environment. In host environment, the result ls / is

bin  boot  cdrom  dev  etc  home  lib  lib32  lib64  libx32  lost+found  media  mnt  opt  proc  root  run  sbin  snap  srv  sys  tmp  usr  var

I try other way like $(ls /), but also with error:

docker exec test bash -c "for i in $(ls /); do echo $i; done"
>! bash: -c: line 2: syntax error near unexpected token `boot'
>! bash: -c: line 2: `boot'
  • 3
    Using output of `ls` is a no go. – Cyrus Mar 10 '23 at 06:48
  • @Cyrus : true, but a more stringent problem is that the `ls` command is executed outside docker. So, while this command indeed is not really meaningful, it does not explain to me why you get **this** syntax error. Out of curiosity, I would run the code with `set -x` enabled. – user1934428 Mar 10 '23 at 06:59

1 Answers1

0

Use single quotes.

docker exec test-container bash -c 'for i in /folder-in-docker/*; do someoperationon($i); done'

Best is to let Bash handle it.

func() {
   for i in /folder-in-docker/*; do someoperationon($i); done
}
docker exec test-container bash -c "$(declare -f func); func"

Note: do not parse ls, do not use backticks, check your scripts with shellcheck.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111