0

So I am having an issue with piping an ls command to grep. Im basically running ls -l within a for loop on a file where some are missing, so it gives me the No file or directory found error for three of the lines. What I can't figure out is how to parse only those lines and output it to another file/variable.

for i in $file
do
    line=`/bin/echo $i | sed 's/source1_dir/dest1_dir/g'`
    /bin/ls -l $line | grep -i "No file"
done

When I try to do that, it outputs the three errors but I am unable to pipe those errors to another file, if that makes sense. I think it's an issue with stderr but I'm not sure.

anishsane
  • 20,270
  • 5
  • 40
  • 73
  • Use `2 > file` or `2 > $var` to save the stderr. – fedorqui Jun 11 '13 at 13:26
  • Thanks I tried that before and nothing outputs to the file, but the errors are gone in the ls output. I did ls -l $line 2> file and the file outputs nothing when I do cat file – outofcontrol19 Jun 11 '13 at 13:37
  • 1
    What I see is that `line='/bin/echo... '` should be `line=$(/bin/echo ...)` if you want `$line` to interpret the result of the command. – fedorqui Jun 11 '13 at 13:40
  • 1
    Your line should be within backticks ` not ' else do like fedorqui says – user568109 Jun 11 '13 at 13:44

2 Answers2

5

With bash, you can simply use |& to get both stdout and stderr in the command after the pipe.

But it might be more useful to use a test:

if [[ -e "$line" ]]; then
    ls -l "$line"
else
    echo "File $line doesn't exist"
fi
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
2

Use stderr redirect. Something like:

/bin/ls -l $line 2>&1 | grep -i "No file"