简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM