Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid No such file or directory in linux

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
like image 264
Jananath Banuka Avatar asked Oct 28 '25 10:10

Jananath Banuka


2 Answers

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.

like image 110
Simon W Avatar answered Oct 31 '25 02:10

Simon W


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

like image 26
haxordan Avatar answered Oct 31 '25 00:10

haxordan