Search code examples
bashio-redirectionquotingsubshell

Bash command fails with bash -c but works in an interactive shell


I have this fairly simple command that, when ran inside bash, outputs the remaining disk space to stdout:

echo -n "External1TB: $(grep -Poi '(\/mnt\/External1TB\s+)\K(.*)' <(df -H --output=target,avail))B"

I'm using process redirection <() to pipe the output of df to grep, which then processes the output and filters out just the remaining space. All of that is wrapped inside a subshell $() and fed to echo so I can prepend the output with a disk name.

Example output: External1TB: 882GB

It works fairly well when ran inside an interactive bash shell, however if I try to run it using bash -c, like so:

bash -c "echo -n "External1TB: $(grep -Poi '(\/mnt\/External1TB\s+)\K(.*)' <(df -H --output=target,avail))B"",

the output is always: External1TB:. It seems that either grep or df fail for some reason.

What am I doing wrong?


Solution

  • Your quoting for the inner part needs to be escaped:

    bash -c "echo -n \"External1TB: $(grep -Poi '(\/mnt\/External1TB\s+)\K(.*)' <(df -H --output=target,avail))B\"",
    

    Alternatively, consider putting at least parts of this into a function or a script so that you don't need to stack string escaping upon string escaping.