I wanted to capture some data from various servers using ssh and run some commands with some conditions.
I don't want to do:
if ssh $host test -f /file; then
# If file exists
var=$(ssh $host long pipeline)
else
# if it doesn't
var=$(ssh $host another long pipeline)
fi
because it will make the process longer. I want to do the if else on the remote machine instead.
I've tried several approaches but I got no luck.
var=$(ssh $host if [ -f /file ]\; then long pipeline1 \; else long pipeline2 \; fi)
Based on this answer, it works but the last command of pipeline1 assumes that else and the rest of pipeline2 as its arguments.
command: can't read else: No such file or directory
...
command: can't read fi: No such file or directory
Then I tried this
var=$(ssh $host test -f /file \&\& pipeline1 \|\| pipeline2)
Again, last command of pipeline1 considered || as its argument.
I also tried below (based on this), which is working:
do_this () {
if [ -f /file ]; then
pipeline1
else
pipeline2
fi
}
var=$(ssh $host "$(set); do_this")
Yet it prints unwanted error messages which don't affect my variable, but it's ugly for my script.
bash: line 1: BASHOPTS: readonly variable
bash: line 8: BASH_VERSINFO: readonly variable
bash: line 24: EUID: readonly variable
bash: line 71: PPID: readonly variable
bash: line 82: SHELLOPTS: readonly variable
bash: line 92: UID: readonly variable
Any suggestions?
Update
I think I have to include what my pipeline is, basically it just a bunch of text processing:
cat file | grep "something" | sed 's/.*="\(.*\)"/\1/' | tr ' ' '-'
As per answer from Jetchisel, in short, i had to wrap my commands with single quote.
var=$(ssh $host 'if [ -f /file ]; then cat file | grep "something" | sed 's/.*="\(.*\)"/\1/' | tr ' ' '-' ; else cat otherfile | ... ; fi'
I got tr: invalid option -- ';'. tr treated ; as its argument.
It works using heredoc:
var=$(ssh $host <<-EOF
if [ -f file ]; then
pipeline1
else
pipeline2
fi
EOF
)
Yet it broke vim's coloring because of the regex I use in sed. I will accept heredoc as the answer for now.
Update 2: I believe my question is not a duplicate of Multiple commands in sshpass, my case is more specific, while the other thread ask it in general.
catfor starters,grepandsedcan parse the file just fine.if grep -q PATTERN INPUT; then sed .....; fiAlthoughawkalone can probably do what pipeline...