I'm trying to check if a particular line exists in filename on a host. So only if the particular pattern is found from the grep command a dummy.txt will be created. Then I want to check if dummy.txt exists as a condition and proceed.
But even though dummy.txt is getting created its not being found by the if statement :
if {[file exists $fileName] }
and the control is transferred to the else block. What could be the reason? Is there any easier method to achieve what I'm trying to ?
set Host [lindex $argv 0 ]
spawn ssh -o StrictHostKeyChecking=no userid@$Host
expect "*assword*"
send "password\n"
expect "+"
send "cd path/that/contains/filename\n"
expect "*$*"
send "pwd\n"
set fileName dummy.txt
send {grep '\[abc\]' filename | wc -l | { read line; [ "$line" != "0" ] && echo "$line"> dummy.txt; }}
send "\n"
expect "+"
send {grep 'xyz' filename | wc -l | { read line; [ "$line" != "0" ] && echo "$line"> dummy.txt; }}
send "\n"
expect "+"
send "chmod 777 dummy.txt\n"
if {[file exists $fileName] } {
send {printf "\nabc xyz already exists"}
send "\n"
expect "+"
send "ls -l\n"
expect "+"
send "rm dummy.txt\n"
expect "+"
send "ls -l\n"
expect "+"
send "exit\n"
} else {
send {printf "cannot find $fileName"}
send "\n"
expect "+"
send {printf "\n[abc]\nxyz\n" >> filename}
send "\n"
expect "+"
send "cat filename\n"
expect "+"
send "exit\n"
}
wc | read ...
you could simply check grep's return code (0 = match found, seeman grep
).