2

I have a pipeline that needs to copy some files from a folder to a new one only if the files exists in the source folder.

This is my script line:

script:
    - cp source_folder/file.txt dest_folder/ 2>/dev/null 

I have also tried this:

script:
    - test -f source_folder/file.txt && cp source_folder/file.txt dest_folder/ 2>/dev/null 

but still fails if the file do not exists.

Cleaning up project directory and file based variables.
ERROR: Job failed: exit code 1

How can I check the file and copy it only if exists?

EDIT:
this command is executed on a server, the pipeline use ssh to log into

1 Answer 1

0

Check for the existence of the file (-f) and, in positive case, copy it.

script:
  - |
    files=(conf.yaml log.txt)

    for file in $files; do
      if [[ -f "source_folder/$file" ]]; then
        cp source_folder/$file dest_folder
      fi
    done

Take a look at other answers for one-shot less-flexible statements.

Note: I haven't tested the script above, but I'm quite accustomed with Gitlab pipeline and bash.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi Davide, thanks for the message. I've tried the code and edited in this way the cp row: ssh christian@$SERVER_IP "cd ~/$SITE_FOLDER; cp public/$file temp/" but it does not copy the file and no error is shown
I have a doubt: should the destination folder be temp (which means ./temp) or should it be /temp?
temp is at the same level of public so maybe I should use ./temp
Try to do it manually with the same bunch of commands: first try to access the server with cli (if possible), then try to use ssh (still manually).
I can access the server with ssh and cli, the pipeline runs different commands before this one on the server. I have tried to run cp public/conf.yml temp and it copy the file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.