Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm executing the below command in the ssh part of my script. The command is meant to cut the file size from ls option and storing it to a variable. Then print the variable:

echo "Enter srouce file";
read src_file;
src_size =`ls -latr $src_file | awk  '{ print $5 }' `;
echo "The source file size is $src_size ";

This works fine when it is executed on the command line.

When I try the same command inside a script via ssh:

ssh user@server "echo "enterfile";read src_file;echo "enter path ";read path;cd $path;src_size=`ls -latr $src_file | awk  '{ print $5 }' ` ; echo The source file size is $src_size;"

This fails. It stores some local temporary value and returns the same instead of correct file size.

share|improve this question
add comment

2 Answers 2

Use a script to avoid messing up your command with quoting issues.

It's cleaner, more manageable and looks better :)!

E.g. just do this:

echo "Enter source file"
read src_file
ssh user@server 'bash -s' < /path/to/local_script.sh "$src_file"

Contents of local_script.sh:

#!/bin/bash
src_file="$1"
src_size =`ls -latr $src_file | awk  '{ print $5 }'`
echo "The source file size is $src_size "

Don't forget to add the path to your local_script.sh :)

share|improve this answer
1  
I'm afraid that in this way you are asking the name of the file from the script and not from the keyboard –  Hastur Jun 23 at 20:29
    
yeah you're right, i'll fix that –  polym Jun 23 at 20:32
add comment

You can't nest double-quotes inside other double-quotes without doing some escaping - and by putting backticks inside double-quotes, they're getting evaluated on the local machine rather than the remote.

Something more like this should do what you're trying to accomplish:

ssh user@server 'echo "Enter file: "; read src_file; echo "Enter path: "; read path; cd $path; src_size=`ls -latr $src_file | awk  "{ print \$5 }"`; echo "The source file size is $src_size;"'

Note that I needed to change the '{ print $5 }' to "{ print \$5 }", escaping the $ because it's now inside double quotes rather than single and I don't want the $5 to be interpretted by the shell.

share|improve this answer
    
he could also use ssh user@server 'echo "Enter file: "; read src_file; echo "Enter path: "; read path; cd $path; src_size=`ls -latr $src_file | awk '"'"'{ print \$5 }'"'"'`; echo "The source file size is $src_size;"'... But then, i'd rather recommend that he'd never have to look at this messy pile of code again :D –  polym Jun 23 at 20:26
1  
Yeah, I upvoted your answer as well - it's just as correct :) –  godlygeek Jun 23 at 20:31
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.