6

So, in bash, this works fine:

(cd /some/dir; ./runscript.sh)

assuming /some/dir/runscript.sh exists.

but

sudo (cd /some/dir; ./runscript.sh)

fails with the error:

-bash: syntax error near unexpected token `cd'

why?

2 Answers 2

9

You need to give it as a command to bash as () is interpreted by bash to run the commands inside parentheses in a subshell:

sudo bash -c '(cd /some/dir; ./runscript.sh)'
2
  • 3
    I was aware of this syntax but still find the question interesting. So, ( is part of bash syntax, rather than being a command that sudo can receive—is that the exact problem?
    – Wildcard
    Commented Dec 16, 2015 at 19:32
  • 2
    @Wildcard exactly..
    – heemayl
    Commented Dec 16, 2015 at 19:33
6

At a lower level, sudo is not running the command(s) in bash (or other shell), but is actually starting a new process based on the "command" you pass it and starting that process with the remaining arguments you pass.

As @heemayl pointed out, you can use the syntax sudo bash -c '(cd /some/dir; ./runscript.sh)'. This is because bash is a legitimate system executable. sudo is unable to create a process named (cd as ( is part of bash syntax, and typically not a valid executable name.

2
  • 3
    Of course, using the parentheses inside the sh -c is kinda pointless, as it gives you a subshell inside a sub process for no apparent reason.
    – kojiro
    Commented Dec 17, 2015 at 1:09
  • 1
    Agreed, it's pointless overhead but makes for a simpler explanation.
    – Jason Rush
    Commented Dec 17, 2015 at 6:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .