Не удается создать временный файл для блока here document
First is simply an oddity with the command cd . If I type in cd , then a space, then press Tab to view the available directories, I get this error message:
bash: cannot create temp file for here-document: Read-only file system
The more troublesome issue has been random closings of the terminal window. It has happened while testing the cd oddity, and also while ssh'd into another server doing simple things like git status and such. [Edit] It seems if I press enter exactly 31 times it triggers the auto closing of the terminal window (verified 3 times now).
I recently upgraded from 12.04 to 14.04 late last week, and this behavior did not occur the entire day I used it after upgrading. This is the first time attempting anything on this computer since that day.
Please advise any other information I can provide, and what I need to do to resolve this.
Just a friendly reminder to make the question title more descriptive, which helps get better responses: "odd terminal behaviour" is not very descriptive.
In order to better diagnose your problem, can you tell me if you are using the default partitioning that Ubuntu set up, are you using whole disk encryption or LVM, and have you done anything to your fstab? What is the output of the mount command?
Thanks for providing that - it looks like no issue with the way the mounts are configured and no problems at mount time but maybe errors with the / (root) mount encountered since then? The remount-ro specifies that the root partition will be remounted as read-only in the event of certain filesystem errors. Doing a fsck from recovery or a Live CD would be good.
6 Answers 6
I rebooted in recovery mode and followed the instructions the system gave me. I ran fsck on /dev/sda2 , and that fixed the problem.
The Read-only file system error is the major clue here. I would guess that your home directory, where bash tries to store your command history and so forth, is inside a read-only partition.
I would guess that it tries to update your recent command history on disk once every 32 commands, which is why it's failing on the 32nd command you type in a session.
Now, a partition may be mounted as read-only if you do it deliberately, but it may also be mounted as read-only if there was an error - this latter behaviour is usually the default for the root partition.
I'd be surprised if you weren't experiencing other problems if your root partition is mounted read-only.
You can try rebooting and checking the disk from the recovery menu. Press and hold shift as the computer boots, right after the BIOS screen disappears and right before the Ubuntu logo appears.
This exact issue happened to me too.
It occurs intermittently.
So I finally had enough with it and decided to reinstall OS - ubuntu-gnome 14.04 (clean).
It fixed it! At least for a few days.. Then that exact same problem occurred again.
So I went to Fry's and got a new hdd (Seagate).
So far so good ( 6 months & counting ).
side note: stock hdd was Toshiba
What I wanted to say is that reinstalling OS or buying a new hard disk is not a proper solution. You may want to comment on other posts and you will be able to comment when you have enough reputation (15).
As others have pointed out, a read-only /tmp filesystem causes further problems.
As for the 31 lines, it's related to gnome-terminal 's internals.
It keeps a certain amount of lines in memory, in a so-called "ring". The rest, lines that scroll out of this ring are placed in a "stream". In older versions of gnome-terminal the stream was pretty much directly written into a file under /tmp , in newer versions there's buffering, compression and encryption before it's written out. (I can't remember off the top of my head whether the file under /tmp is opened when the first chunk of data is written into the stream, or when the stream first tries to actually write to /tmp ; it's a minor implementation detail.)
The size of the ring is always a power of two (each slot containing 1 line of the terminal; except for 1 slot is not used due to technical reasons), and is doubled every time it's required due to the growth of the terminal height (but never shrinks back). E.g., with the default height of 24 lines the ring contains the last 31 lines of output, the rest goes to the stream (eventually to /tmp ). If you increase the window's height to let's say 40 lines, the in-memory ring will grow to accommodate at most 63 entries at a time.
What you experience is that gnome-terminal tries to open a file in /tmp to store the stream, and exits because of the unexpected failure here. Try with a taller window than the default; it'll crash after pressing Enter 63 (or maybe 127) times.
That being said, /tmp should be fixed to be writable (with permissions 1777).
При использовании панели вкладок я получаю эту ошибку:
bash: невозможно создать временный файл для here-документа: на устройстве не осталось места "
Я провел некоторое исследование, и многие люди говорят о файле / tmp, который может быть переполнен. Когда я выполняю, df -h я получаю:
Похоже, что каталог / dev / data собирается взорваться, однако, если я советую:
Кажется, это пусто.
Я новичок в Debian, и я действительно не знаю, как поступить. Я обычно получал доступ к этому компьютеру через ssh. Помимо этой проблемы, у меня есть несколько других с этим компьютером, они могут быть связаны, например, каждый раз, когда я хочу войти в моего пользователя, используя графический интерфейс (с root это работает), я получаю:
Xsession: предупреждение: невозможно записать в / tmp: Xsession может завершиться с ошибкой
Вы хотите запустить что-то вроде du -hxd1 / , нет du /dev/sda2 . /dev/sda2 на самом деле не существует на диске.
Ваша корневая файловая система заполнена, и, следовательно, ваш временный каталог (/ tmp и / var / tmp в этом отношении) также заполнен. Многие сценарии и программы требуют места для рабочих файлов, даже для блокировки файлов. Когда / tmp не переписывается плохие вещи случаются.
Вам нужно выяснить, как вы заполнили файловую систему. Обычно это происходит в / var / log (проверьте, что вы зацикливаете файлы журнала). Или / tmp может быть полным. Однако существует множество способов заполнить диск.
Возможно, вы захотите переразбить, чтобы получить / tmp свой собственный раздел (это старый способ школы, но если у вас достаточно диска, это нормально), или отобразить его в памяти (что сделает его очень быстрым, но начать вызывает проблемы с обменом, если вы переусердствуете с временными файлами).
Привет, я посмотрел обе предложенные вами команды и скажу, что и / tmp, и / var / log совершенно пусты: 60K и 49M соответственно.
Привет еще раз. Я наконец получил это. Я не знаю, почему я поместил весь контент owncloud в / var. Это снова работает!
Эта ранее работающая строка сценария bash
не может создать временный файл для здесь-документа: В доступе отказано
В моем случае был включен IMA ( ima_policy=appraise_tcb параметр ядра) с комбинацией /tmp не быть tmpfs . Но это не совсем обычный случай :).
Я добавил umask 777 перед строкой здесь. После удаления umask ошибка ушла. Итак, извлеченный урок: существует временный файл, созданный для строки here (
Это также влияет на zsh и mksh, а не на ksh93 и tcsh. Не dash, rc, es и yash, а потому, что они используют каналы вместо временных файлов.
В случае ksh93 и tcsh это работает, потому что они открывают файл только один раз в режиме чтения + записи, записывают данные и затем возвращаются к началу.
В моем случае я изменил /tmp разрешения по умолчанию для каталога (я думаю, что я по ошибке изменил на 0777).
Решением было вернуть его обратно к /tmp разрешению по умолчанию , которое равно 1777 в восьмеричном виде (1 = бит закрепления, 7 = R + W + X).
Так что в двух словах sudo chmod -R 1777 /tmp следует решить проблему.
Вы, вероятно, не хотите -R флаг. Нет причин изменять все файлы ниже, /tmp чтобы они были доступны для чтения и записи. Некоторые из этих файлов чувствительны к безопасности ваших пользователей.
Мой личный опыт с этой проблемой был с umask двоичной нотацией, как @ eliptical-view. Я предположил, что написание:
дал бы мне доступ на чтение и запись к файлам, которые я создал, что не так
После того, как я изменил, umask чтобы быть
На самом деле двоичная запись должна пониматься как двоичное дополнение.
Таким образом, в umask маске ниже, когда кто-то пишет 0 для владельца файла, этот пользователь будет иметь полный доступ к файлам, которые он или она создает. Значение 2 означает, что 2-й бит замаскирован, что означает, что в этом случае другим пользователям по умолчанию не разрешается записывать в файлы, которые создает владелец файла.
Спасибо за редактирование и исправление, @Paulo Tomé. Действительно, обычно (и понятно) использовать восьмеричную нотацию umask , поскольку в разрешениях файла Posix участвуют ровно три бита - для владельца, одной из его или ее групп и всех остальных.
Я пытался стереть свободное место на внешнем диске USB 3.0 в утилите дисков OS X (Yosemite). Однако я получаю следующую ошибку:
РЕДАКТИРОВАТЬ: Диск отформатирован как GUID / Mac OS Extended (в журнале) и 1.1 из 2,0 ТБ заняты.
- Знаете ли вы, в чем может быть причина / решение? Восстановление диска не возвращает ошибок.
- Знаете ли вы о терминальной команде, чтобы стереть свободное место?
Влияет ли переключение «игнорировать владение» на Get Info? [Я все еще думаю о «разрешении писать», а не о «сломанном»]
@Tetsujin: Хороший. Я даже не знал этот вариант, пока не нашел его. Это стирает прямо сейчас. Хотите добавить ответ?
Первой моей мыслью было бы, что это какая-то ошибка прав доступа .
- Диск отформатирован как NTFS или ExtFS и т. д.
- Система не имеет прав записи на само устройство
Во-первых, самым простым, если не самым дешевым решением было бы что-то вроде Paragon NTFS или ExtFS или Tuxera NTFS.
Если это чисто проблема с правами доступа / владением, то для съемного диска самое простое решение - установить «Игнорировать владение» в окне «Информация». Этого должно быть достаточно для того, чтобы система могла выполнять запись на диск для безопасного удаления.
Если вы запустите утилиту диска из командной строки, вы получите то же поведение со следующим выводом:
У меня такая же проблема. Перезапустите, и пока машина перезагружается, одновременно удерживайте нажатой клавишу «Command» и клавишу «R». Удерживайте нажатой, пока не появится значок Apple, затем отпустите обе клавиши. Появятся четыре варианта - выберите Дисковую утилиту. Продолжите процедуру удаления свободного пространства как обычно.
Первая попытка сработала для меня, после 6 месяцев разочарования.
Мне больше повезло с этим методом, чем при нормальной загрузке, но в большинстве случаев он все еще дает ошибки.
Когда я пытаюсь это сделать, затем выбираю свой Mac HD, я обнаруживаю, что кнопка «Удалить свободное место» отключена в приложении Дисковая утилита.
Откуда ты знаешь, что стерто свободное пространство? Если бы пространство было свободным для начала, каким инструментом вы бы использовали, чтобы определить, что оно было правильно перезаписано?
Откуда ты знаешь, что стерто свободное пространство? Если бы пространство было свободным для начала, каким инструментом вы бы использовали, чтобы определить, что оно было правильно перезаписано?
When POSIX shell scripts use here documents , a temporary file is created. Is there any way to environmentally control WHERE (path) these temporary files get created?
I am currently developing an Ant script that launches remote POSIX operating system shell scripts on Linux, SunOS, HP-UX and AIX .Scripts compile C++ source code using GNU Autoconf/Automake . The generated configure script itself makes use of several here documents . If any of those here documents cannot create a file at /var/tmp (on SunOS) a chain reaction of failed configure script tasks results in missing binary files due to failed attempts to compile C++ code. :-(
So,I could keep cleaning up /var/tmp . But these POSIX servers are heavily used by nightly, long-running jobs that temporarily eat /var/tmp space then give it up, sporadically causing No space left on device outages. Obviously, some system administration could alleviate this problem--grow the /var/tmp partition perhaps.
But that is neither here, nor there, really; I want to remove the dependency upon other file systems/partitions entirely . I want my entire scripted system to be self-contained, so that hiccups with /var/tmp space do not matter to my Ant system when a remote POSIX platform runs out of a puny amount of /var/tmp space. Nonsense.
In a perfect POSIX world, I should be able to control the location (path) used by all shell script 'here documents' right? There has to be a configurable way; but all I have found is a way to control the location of 'vi' temporary space using an .exinit file with a directory=~/tmp command. Isn't the same idea implemented by the original UNIX gods for the POSIX shell script here documents?
Tried the following ideas; they didn't make a difference:
To reproduce the problem, fill /var/tmp (your POSIX system might be using /tmp) 100%, then try saving the following script to tst.sh. Then make it executable with chmod +x tst.sh. Then run tst.sh by typing it at the shell prompt, of course.
Читайте также: