3

Currently I have a script that does some extra processing, but ultimately calls the command the user passed (FYI, this is to run some commands in a docker container, but we'll call it foo.sh):

#!/usr/bin/env bash
# ...
runner "$@"

This works great (e.g. foo.sh echo HI), until the users wants to pass multiple commands to be run:

e.g.: foo.sh echo HI && echo BYE

&& is of course interpreted by the ambient shell before being passed into arguments.

Is there a workaround or means of escaping && that might work?

3
  • 1
    runner bash -c "echo HI && echo BYE" Commented May 16, 2019 at 1:54
  • 1
    ...otherwise, you're writing a whole new command language. Which I've actually done before -- execline is a good source of inspiration to consider, built for graceful use in just the kind of scenario your question anticipates. (To be clear, execline is not mine, but something I've used as food for thought in building a toolset for related purposes) Commented May 16, 2019 at 1:55
  • 1
    With respect to the general limitation, though, it's a feature, not a bug. If "$@" could expand to content parsed as syntax, passing untrusted data around in bash would be effectively impossible. Commented May 16, 2019 at 2:05

1 Answer 1

3

An idiom that often comes in handy for this kind of case:

cmds_q='true'
add_command() {
  local new_cmd
  printf -v new_cmd '%q ' "$@"
  cmds_q+=" && $new_cmd"
}

add_command echo HI
add_command echo BYE
runner bash -c "$cmds_q"

The big advantage here is that add_command can be called with arbitrary arguments (after the first one defining the command to run, of course) with no risk of those arguments being parsed as syntax / used in injection attacks, so long as the caller never directly modifies cmds_q.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.