-1

I am trying to test if a file fails to transfer using SCP.

I noticed if I use a un-initialized variable, I get exit 0 even though the SCP fails.

For example, I have an empty variable called uninitialized_var

[root@centos_8_0 scripts]# echo $uninitialized_var

If I try to use it in SCP command, the command appears to work, returns exit 0, however no file is copied due to non-existent path. If I use a hard path that does not exist, it will fail.

[root@centos_8_0 scripts]# scp root@centos_8_1:/root/test/stack_test/file_20210302.csv $uninitialized_var/file_20210302.csv
file_20210302.csv                                                                                                                                                     100%    0     0.0KB/s   00:00

[root@centos_8_0 scripts]# echo $?
0

Is there a way to test if copy succeeded? Currently I am using:

  
if [[ $? != 0 ]]; then... 
however like I said it returns 0.

Is there a reason why it returns 0?

2 Answers2

2

The variable will be expanded by the shell and in this case prepended to /file_20210302.csv. This means that your destination path is just /file_20210302.csv. You are performing this action as root which has write permission to /. The files are being copied and placed in your root directory, no error is occurring so the exit status is 0.

I tested this with

scp user@example.com:/home/user/test_file  $uninitialized_var/tmp/test_file

and it worked as expected, placed the file in /tmp and exit status 0.

user620588
  • 66
  • 1
0

Assuming that you're using bash, you can supply a default value for the variable, to be used if the variable is not set.

echo ${uninitialized_var:-NOT_SET}/file_20210302.csv

If the variable is not set, it will "return" the value "NOT_SET" instead.
You can also supply a more sensible default value, e.g.

scp root@centos_8_1:/tmp/file_20210302.csv ${uninitialized_var:-/tmp}/file_20210302.csv

If uninitialized_var is set, scp will write to that folder.
If not, it will write the file to /tmp.

Refer to Shell Parameter Expansion.

Phill W.
  • 1,479
  • 7
  • 7