Меню

Shell init ошибка получения текущей директории getcwd

Столкнулся с проблемой:

shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

или

chdir: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

или

sh: 0: getcwd() failed: No such file or directory

Попробовал перейти в другую папку:

# cd /home/captain/some_dir

Получил ошибку:

chdir: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

Так же, попробовал использовать TAB для автоподстановки пути:

# cd /hsymlink-hook: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

И так, данная проблема возникает когда команда пробует выполнять что-то уже не из существующей папки. По этому, решение очень простое — нужно перейти в любой другой существующий каталог

# cd ~

и

# pwd

/home/captain

или:

# cd $(pwd)

Смотрим теперь:

# ls -l /home/captain/some_dir

ls: cannot access /home/captain/some_dir: No such file or directory

Вот и все, я завершаю свою тему «Ошибка shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory».

  • Архив новостей

    Архив новостей

  • Свежие записи

    • Pull/Push AWS ECR образов через AWS Route53 CNAME
      17.11.2021
    • openpgp: signature made by unknown entity в Terraform
      09.11.2021
    • Установка Terraformer в Unix/Linux
      31.05.2021
    • Установка ArgoCD в Unix/Linux
      06.01.2021
    • Установка tfswitch в Unix/Linux
      08.12.2020
  • Мета

    • Войти
    • Лента записей
    • Лента комментариев
    • WordPress.org

I have a simple script:

#!/bin/bash
for server in $(~/.ansible/ansible_hosts)
do
    ssh $server "hostname; readlink /opt/mydir/mylink;"
done

It works fine — the program returns the correct hostname and link — except that I get the following error on some but not all of the servers:

shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

All the directories exist. One of the most common suggestions has been to add a cd, a cd -, or a cd /. All that happens when that step is added is an additional:

chdir: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

I tried kickstarting the nfs daemon on the off chance that there was some confusion about my homedir and substituted /etc/init.d in case the problem was with /opt. No difference

This would simply be an annoyance except that when I try to use an ansible playbook instead of a simple ssh command it fails for that server.

Any insights would appreciated.

Here’s an error reported by one of our regular reader Anu. She says, cluster-fork  w command ends up with an error “shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory“.

Here’s the complete snapshot of the error:

$cluster-fork w
compute-0-0: shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
down
compute-0-1: shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

Solution:

This error mostly occurs when the directory in which this command was executed does not exist anymore. For example, assume that you had changed directory to 'test' and issued cluster-fork command. During the execution of cluster-fork, if the directory test was removed (may be a program that regularly cleans disk space or mistakenly deleted from a different terminal), then 'getcwd' will not be able to return the current working directory. Hence, cluster-fork will return an error “getcwd: cannot access parent directories: No such file or directory”.

To fix this error, one has to just get out of that non-existent directory. Usually by issuing 'cd' command to get to the home directory and execute cluster-fork command.

Note:

Using cd .. will not work and you will still end up with the same error message.

The other day we started a new course here at </salt> And the first day we are used to seeing some confusion from the developers and the odd strange, wrongly configured computer (by us). But the error in the title of this blog post:

 getcwd: cannot access parent directories: No such file or directory

had me scratching my head for quite some time. Until I realized that the error message states what was wrong.

The whole thing is quite simple: the team I was helping got this, or similar errors whatever command they tried to run:

ls?

shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

open .?

LSOpenURLsWithRole() failed with error -50 for the URL ./.
shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

Even pwd was just barfing out error:

/Users/marcus/adir
shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

But that last part had me thinking, maybe the directory was gone somehow?

Let’s try it:

  1. Open a terminal window and go cd ~
  2. Create a new directory and cd into it mkdir adir && cd adir
  3. Now, open a new terminal window and go to that same place cd ~
  4. Now, delete the directory rm -rf adir
  5. Finally — go back to the previous window and try to do just about any command you can come up with and it will give you errors like the ones above.

Not surprisingly, since you are in essence running the command in a directory that doesn’t exist.

Easy to mix up when you are new to the terminal — and apparently hard to grasp even if you have been using the terminal for years…

This isn’t an error I can reproduce on all macs, was able to run this no problem on a second laptop yesterday, and is an error I get from multiple locations attempting to do multiple tasks that are all failing

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied

I first noticed this when trying to install phantomjs via npm:

$ sudo npm install -g phantomjs
/usr/local/bin/phantomjs -> /usr/local/lib/node_modules/phantomjs/bin/phantomjs

> phantomjs@1.9.10 install /usr/local/lib/node_modules/phantomjs
> node install.js

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied

node.js:815
    var cwd = process.cwd();
                  ^
Error: EACCES, permission denied
    at Function.startup.resolveArgv0 (node.js:815:23)
    at startup (node.js:58:13)
    at node.js:906:3

npm ERR! Darwin 13.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "-g" "phantomjs"
npm ERR! node v0.10.32
npm ERR! npm  v2.0.0
npm ERR! code ELIFECYCLE
npm ERR! phantomjs@1.9.10 install: `node install.js`
npm ERR! Exit status 8
npm ERR! 
npm ERR! Failed at the phantomjs@1.9.10 install script.
npm ERR! This is most likely a problem with the phantomjs package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node install.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls phantomjs
npm ERR! There is likely additional logging output above.

A similar issue also occurs when installing selenium-standalone package from node.js:

$ sudo npm install -g selenium-standalone
/usr/local/bin/start-selenium -> /usr/local/lib/node_modules/selenium-standalone/bin/start-selenium

> selenium-standalone@2.43.1-2.9.0-1 install /usr/local/lib/node_modules/selenium-standalone
> node install.js

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied

node.js:815
    var cwd = process.cwd();
                  ^
Error: EACCES, permission denied
    at Function.startup.resolveArgv0 (node.js:815:23)
    at startup (node.js:58:13)
    at node.js:906:3

Which seems to indicate it’s not related to any specific node.js package, however other packages install fine(such as grunt-cli)

Finally in searching for answers to this, I’ve also found a few things which had problems but weren’t able to solve the problem in question:

  1. Fixed permissions on my hard drive via disk utility, issues were found and fixed
  2. rebooted into recovery and repaired my disk, which also had issues
  3. sudo /usr/libexec/locate.updatedb had the same issue. people recommended enabling root, and running it. This allowed that command to run correctly, and subsequent runs did not have the same error anymore. However trying this same process with npm did not lead help

I’m not sure what else could be causing the problem.

Вопрос:

У меня есть простой script:

#!/bin/bash
for server in $(~/.ansible/ansible_hosts)
do
ssh $server "hostname; readlink /opt/mydir/mylink;"
done

Он отлично работает – программа возвращает правильное имя хоста и ссылку – за исключением того, что я получаю следующую ошибку на некоторых, но не на всех серверах:

shell-init: ошибка получения текущего каталога: getcwd: не может обращаться к родительским каталогам: нет такого файла или каталога

Все каталоги существуют. Одним из наиболее распространенных предложений было добавление cd, cd – или cd/. Все, что происходит при добавлении этого шага, является дополнительным:

chdir: ошибка получения текущего каталога: getcwd: не может обращаться к родительским каталогам: нет такого файла или каталога

Я пробовал запускать демона nfs вовремя, чтобы возникла некоторая путаница в отношении моего homedir и заменила /etc/init.d в случае, если проблема была с /opt. Без разницы

Это просто было бы досадой, за исключением того, что когда я пытаюсь использовать незанятую пьесу вместо простой команды ssh, она терпит неудачу для этого сервера.

Любые идеи были бы оценены.

Ответ №1

Я считаю, что ошибка вообще не связана с script. Проблема в том, что каталог, в котором вы находитесь, когда вы пытаетесь запустить script, больше не существует. например, у вас есть два терминала, cd somedir/ на первом, а затем mv somedir/ somewhere_else/ на втором, а затем попытайтесь запустить что-либо в первом терминале – вы получите это сообщение об ошибке.

По крайней мере, это было в моем случае.

Ответ №2

Вы выполняете это как script.. $(~/.ansible/ansible_hosts). $() Означает, что bash попытается выполнить это script, а затем вывести результаты.

Но это не script, правильно? Это список хостов!

Просто добавьте слово cat, и оно должно работать.

#!/bin/bash
for server in $(cat ~/.ansible/ansible_hosts)
do
ssh $server "hostname; readlink /opt/mydir/mylink;"
done

shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
While working on setting new squid transparent proxy in network.I faced an unusual error while restarting the Squid service.
The getcwd() function copies an absolute pathname of the current working directory to the array pointed to by buf, which is of lengthsize. (For more info Read man page of getcwd)

Solution : To solve this issue. I change the directory to / root by using command cd / .After this I again restarted the squid service.The problem did not occur then.

Below is the reference from my system

[root@localhost modules]# /etc/init.d/squid restart
shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
Stopping squid: ................                           [  OK  ]
Starting squid: .                                          [  OK  ]
[root@localhost modules]# cd /
[root@localhost /]# /etc/init.d/squid restart
Stopping squid: ................                           [  OK  ]
Starting squid: .                                          [  OK  ]
[root@localhost /]#

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Sev 004 tout ошибка
  • Setupui dll autocad ошибка