3

I am trying to chmod into a file. Sometimes it doesn't exist. In a case like this, I want it not to give any error. That means the chmod should only be executed if the file is exist.

I am doing this with gitlab-runner, but still it executes the shell scripts so this is something to be fixed from linux side, not from gitlab

Here is what I try to do

ssh-publickey:
  stage: ssh-publickey
  script: 
    - pwd
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh # i want to check before executing this command
    - sudo chmod 700 ~/.ssh/gitlab.pem
    - echo $PRIVATEKEY > ~/.ssh/gitlab.pem
Jananath Banuka
  • 493
  • 3
  • 11
  • 22

3 Answers3

2

You could use the chmod flag -f to ignore errors i.e. don't print an error message if the file does not exist. However, the command will still have an exit status of 1 as it did not find a file. If you want to avoid that and always get a status code of 0 even if the file does not exist, you could do the following:

chmod -f 700 ~/.ssh | :

The ":" is the linux null-command, which will exit with code 0.

Simon W
  • 174
  • 6
1

You can also wrap the chmod command in an if statement to check if the file/directory exists before running it:

if [ -d ~/.ssh ] ; then chmod 0700 ~/.ssh ; fi

haxordan
  • 11
  • 3
0

Add || true add the end of the command

so in your case:

    - chmod 700 ~/.ssh || true

will ignore any error

Bash ignoring error for a particular command

b2f
  • 196
  • 2
  • 10