Question

I need to write an execute some command in bash file and ignore the inputs.

Example

pvs --noheadings -o pv_name,vg_name,vg_size 2> /dev/null

The above command works great in command line, but when I write the same in shell, it gives me an error

like

Failed to read physical volume "2>"
Failed to read physical volume "/dev/null"

I guess it looks it as an part of the whole command. Can you please give me some suggestions on how to rectify it?

Thanks in advance.

FULLCODE

#------------------------------

main() {
    pv_cmd='pvs'
    nh='--noheadings'
    sp=' '
    op='-o'
    vgn='vg_name'
    pvn='pv_name'
    pvz='pv_size'
    cm=','
    tonull=' 2 > /dev/null '
    pipe='|'

    #cmd=$pv_cmd$sp$nh$sp$op$sp$vgn$cm$pvn$cm$pvz$sp$pipe$tonull  #line A
    cmd='pvs --noheadings -o vg_name,pv_name,pv_size 2> /dev/null' #line B
    echo -n "Cmd="
    echo $cmd
    $cmd

}

main

#-----------------------------------------------------

If you look at the Line A & B both the versions are there, although one is commented out.....

Was it helpful?

Solution

You can't include the 2> /dev/null inside the quoted string. Quote removal happens after redirections are processed. You'll have to do

cmd='pvs --noheadings -o vg_name,pv_name,pv_size'
$cmd 2> /dev/null

for redirection to work properly.

OTHER TIPS

The way you did it, 2> and /dev/null will be parsed as arguments. But you want 2> /dev/null to be bash code, not program argument, so

instead of

 $cmd

you should

 eval $cmd

That is how things work.

Or if the echo thing is for debugging, you can just set -o xtrace before the command and set +o xtrace after it. And do it the normal way instead of stuffing a string.

I think what's going on is that there is some character inside the line that is either not visible to us or the > is a different character than it appears. After all the shell should swallow the redirect before the command gets to see it, but the command sees 2> and /dev/null as [PhysicalVolume [PhysicalVolume...]]. Alternatively the redirection could be passed quoted (so it loses the special meaning to the shell and gets passed on), see chepner's answer.


tonull=' 2 > /dev/null '

is the issue. Exactly as chepner guessed.

eliminate space between 2 and >

pvs --noheadings -o pv_name,vg_name,vg_size 2>/dev/null
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top