I need to go another server and perform a word count. Based on the count variable I will perform a if else logic. However i am unable to do a word count and further unable to compare the variable value in if condition.
Error:
wc: cannot open the file v.txt
Script:
#!/bin/bash
ssh u1@s1 "cd ~/path1/ | fgrep-f abc.csv xyz.csv > par.csv | a=$(wc -l par.csv)| if ["$a" == "0"];
then echo "success"
fi"
First, although the
wcprogram is named for 'word count',wc -lactually counts lines not words. I assume that is what you want even though it isn't what you said.A shell pipline
one | two | threeruns things in parallel with (only) their stdout and stdin connected; thus your command runs one subshell that changes directory to~/path1and immediately exits with no effect on anything else, and at the same time tries to runfgrep-f(see below) in a different subshell which has not changed the directory and thus probably can't find any file, and in a third subshell does the assignment a= (see below) which also immediately exits so it cannot be used for anything.You want to do things sequentially:
Note several other important changes I made:
the command you give
sshto send the remote must be in singlequotes'not doublequotes"if it contains any dollar as yours does (or backtick); with"the$(wc ...)is done in the local shell before sending the command to the remoteyou don't need
~/in~/path1becausessh(or reallysshd) always starts in your home directorythere is no common command or program
fgrep-f; I assume you meant the programfgrepwith the flag-f, which must be separated by a space. Alsofgrepalthough traditional is not standard (POSIX);grep -Fis preferredyou must have a space after
[and before]However, this won't do what you probably want. The value of
$awill be something like0 par.csvor1 par.csvor999 par.csv; it will never equal0so your "success" branch will never happen. In addition there's no need to do these in separate commands: if your actual goal is to check that there are no occurrences in xyz.csv of the (exact/non-regexp) strings in abc.csv both in path1, you can just dogrep(always) sets its exit status to indicate whether it found anything or not; flag-qtells it not to output any matches. Sogrep -q ...just sets the status to true if it matched and false otherwise; using!inverts this so that ifgrepdoes not match anything, thethenclause is executed.If you want the line count for something else as well, you can do it with a pipe
Not only does this avoid the temp file, when the input to
wcis stdin (here the pipe) and not a named file, it outputs only the number and no filename --999rather than999 par.csv-- thus making the comparison work right.