1

I have written shell script which reads commands from input file and execute commands. I have command like:

cat linux_unit_test_commands | grep "dmesg" 

in the input file. I am getting below error message while executing shell script:

cat: |: No such file or directory
cat: grep: No such file or directory
cat: "dmesg": No such file or directory

Script:

 #!/bin/bash

 while read line
 do
     output=`$line`
     echo $output >> logs
 done < $1

Below is input file(example_commands):

ls
date
cat linux_unit_test_commands | grep "dmesg"

Execute: ./linux_unit_tests.sh example_commands

Please help me to resolve this issue.

Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

2

Special characters like | and " are not parsed after expanding variables; the only processing done after variable expansion is word splitting and wildcard expansions. If you want the line to be parsed fully, you need to use eval:

while read line
do
    output=`eval "$line"`
    echo "$output" >> logs
done < $1
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You might be wondering why its not working with cat command. Then here is the answer for your question.

output=`$line` i.e. output=`cat linux_unit_test_commands | grep "dmesg"`

here the cat command will take (linux_unit_test_commands | grep "dmesg") all these as arguments i.e. fileNames.

From Man page:

SYNTAX : cat [OPTION]... [FILE]...

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Script is OK!

#!/bin/bash

while read line;
do
    output=`$line`
    echo $output >> logs
done < $1

To make it work you need to change 'cat: "dmesg": No such file or directory' to 'grep "dmesg" linux_unit_test_commands'. It will work!

cat linux_unit_test_commands

ls
date
grep "dmesg" linux_unit_test_commands
PravinY
  • 500
  • 1
  • 5
  • 9