Actual return code for SCP

一笑奈何 提交于 2019-12-13 01:55:20

问题


I am writing a bash script that goes through a list of filenames and attempts to copy each file using scp from two servers into a local folder. The script then compares the local files to each other. Sometimes however, the file will not exist on one server or the other or both.

At first, I was using this code:

scp $user@$host:/etc/$file ./$host/conf/ 2>/tmp/Error 1>/dev/null
error=$(</tmp/Error) # error catching
if [[ -n "$error" ]]; then echo -e "$file not found on $host"; fi

But I found that some (corporate) servers output a (legalese) message (to stderr I guess) every time a user connects via scp or ssh. So I started looking into utilizing exit codes.

I could simply use

scp $user@$host:/etc/$file ./$host/conf/ 2>/tmp/Error 1>/dev/null
if [[ $? -ne 0 ]]; then echo -e "$file not found on $host"; fi

but since the exit code for "file does not exist" is supposed to be 6, I would rather have a more precise

scp $user@$host:/etc/$file ./$host/conf/ 2>/tmp/Error 1>/dev/null
if [[ $? -eq 6 ]]; then echo -e "$file not found on $host"; fi

The problem is that I seem to be getting an exit code of 1 no matter what went wrong. This question is similar to this one, but that answer does not help me in Bash.

Another solution I am considering is

scp $user@$host:/etc/$file ./$host/conf/ 2>/tmp/Error 1>/dev/null
error=$(</tmp/Error) # error catching
if [[ ${error: -25} = "No such file or directory" ]]; then echo -e "$file not found on $host"; fi

But I am concerned that different versions of scp could have different error messages for the same error.

Is there a way to get the actual exit code of scp in a Bash script?


回答1:


Per the comments (@gniourf_gniourf, @shelter, @Wintermute) I decided to simply switch tools to rsync. Thankfully the syntax doesn't need to be changed at all.

23 was the error code I was getting when files didn't exist so here is the code I ended up with

rsync -q $user@$host:/etc/$file ./$host/conf/ 2>/tmp/Error 1>/dev/null
if [[ $? -eq 23 ]]; then echo -e "$file not found on $host"; continue; fi



回答2:


I'm seeing 1 for "file not found" not found, you can do testing for these sorts of things against localhost, if you need to differentiate different errors capture stdout instead.

if $err=`scp $host:$file 2>&1`
then 
  echo "copied successfully
else
case "$err" in 
  *"file not found"* )
     echo "$file Not Found on $host"
     ;;
  *"Could not resolve hostname"* )
    echo "Host not found: $host"
    ;;
  "Permission denied "* ) 
    echo "perm-denied! $host" 
    ;;
  * )
    echo "other scp error $err"
    ;;
esac

this isn't going to work if you have a different locale with different messages.



来源:https://stackoverflow.com/questions/27713728/actual-return-code-for-scp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!