4

I want to list the files on the remote machine using bash script without entering password.

I am using following command to do it

sshpass -p password ssh user@ubuntusite.net  "ls /usr/local/"

I want to get the exit code from the above command to know my command (ls /usr/local) fails or get passed.

How to do it? Kindly help me

Galet
  • 5,853
  • 21
  • 82
  • 148
  • 2
    Why are you using sshpass rather than passwordless RSA/DSA keys? – John Kugelman Jan 29 '18 at 13:23
  • 1
    And [don't use `ls` in scripts](https://mywiki.wooledge.org/ParsingLs) either. – tripleee Jan 29 '18 at 13:37
  • Can you give us some context for this? Where does the above command fit into a larger script? A bigger picture will help us provide more appropriate answers. – ghoti Jan 29 '18 at 14:08
  • 1
    There are indeed use cases for `sshpass`. Also using `ls` in scripts is perfectly okay for testing or for output. It can well be a placeholder for a more useful command. I'm pretty sure the OP simply asked how to get the return value of ls through to the calling shell when using `sshpass`. – Pavel Šimerda Apr 09 '19 at 09:22

2 Answers2

2

For example:

[STEP 101] # sshpass ssh 127.0.0.1 true
[STEP 102] # echo $?
0
[STEP 103] # sshpass ssh 127.0.0.1 false
[STEP 104] # echo $?
1
[STEP 105] # sshpass ssh 127.0.0.1 exit 11
[STEP 106] # echo $?
11
[STEP 107] #
pynexj
  • 19,215
  • 5
  • 38
  • 56
0

If I understood you clearly, you need not ls output, just only exit code, right?

So, try this:

sshpass -p password ssh user@ubuntusite.net  "ls /usr/local/ &>/dev/null && echo $? || echo 1"

It will return and print 0 if command passed, print 1 in another case.

Viktor Khilin
  • 1,760
  • 9
  • 21