- Ubuntu: SIOCADDRT: File exists Error and Solution
- Understanding SIOCADDRT: File exists Message
- Display Current Routing Table
- Delete Wrong Routing IP Address
- Add Correct Routing IP
- Network Configuration File
- Say Hello To NetworkManager
- nm-applet
- See also:
- Проверка существования файла Bash
- Проверка существования файла Bash
- Проверка наличия файла
- Проверка файла на пустоту
- Выводы
- Linux error file exists
- No such file or directory? But the file exists!
- 8 Answers 8
- How do I tell if a regular file does not exist in Bash?
- 20 Answers 20
Ubuntu: SIOCADDRT: File exists Error and Solution
I ‘m typing the following command under Ubuntu Linux:
route add default gw 192.168.3.2 eth0
But it is giving me out the following error:
SIOCADDRT: File exists
How do I fix this problem?
This error normally displayed when you try to modify or or add a new routing IP address. For example, when you set the same route multiple times you will get this error.
Understanding SIOCADDRT: File exists Message
- SIOC: Serial Input Output Controller.
- ADD: ADD (addition).
- RT: RouTe (routing ip).
- File exists – Routing is already configured so delete wrong one and add the new one.
Display Current Routing Table
Open a command-line terminal (select Applications > Accessories > Terminal), and then type the following command to see your current routing table:
$ netstat -r
OR
$ ip route list
Delete Wrong Routing IP Address
Use the following syntax:
$ sudo ip route delete
To delete default route 192.168.1.0/24 via eth0, enter:
$ sudo ip route delete 192.168.1.0/24 dev eth0
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Add Correct Routing IP
Type the following command:
$ sudo ip route add default via 192.168.3.2
OR
$ sudo route add default gw 192.168.3.2 eth0
Network Configuration File
Edit, /etc/network/interfaces file and setup the correct routing address:
Say Hello To NetworkManager
Networking on Linux can be painful, especially in comparison to other operating systems. You should never need to use the command line or configuration files to manage your network (unless you want to!); everything should “Just Work” as automatically as possible and never stop you from doing what you want to do. NetworkManager attempts to make networking as invisible as you want it to be. Whether at home, work, or on the move, NetworkManager automatically connects to the last network you told it to connect to. From wired to wireless to mobile broadband to Bluetooth, NetworkManager has you covered.
nm-applet
The nm-applet is the applet which appears in the system tray. One can right-click the applet (the icon of two computers, one below to the other on the left-side) to manage and activate/deactivate your network connections. Clicking on NM-applet will give you the types of connection/hardware you have available. To modify your settings for eth0 or eth1 interface, right click on NM-applet > select Edit Connections. It will brings up the network-connections as follows:
Fig.01: Pain-Free Networking with NetworkManager
Fig.02: Editing eth0 network connection
Fig.03: Setting up default gateway (routing table)
See also:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Проверка существования файла Bash
В операционных системах GNU/Linux любые объекты системы являются файлами. И проверка существования файла bash — наиболее мощный и широко применяемый инструмент для определения и сравнения в командном интерпретаторе.
В рамках интерпретатора Bash, как и в повседневном понимании людей, все объекты файловой системы являются, тем, чем они есть, каталогами, текстовыми документами и т.д. В этой статье будет рассмотрена проверка наличия файла Bash, а также его проверка на пустоту, и для этого используется команда test.
Проверка существования файла Bash
Начать стоит с простого и более общего метода. Параметр -e позволяет определить, существует ли указанный объект. Не имеет значения, является объект каталогом или файлом.
#!/bin/bash
# проверка существования каталога
if [ -e $HOME ]
then
echo «Каталог $HOME существует. Проверим наличие файла»
# проверка существования файла
if [ -e $HOME/testing ]
then
# если файл существует, добавить в него данные
echo «Строка для существующего файла» >> $HOME/testing
echo «Файл существует. В него дописаны данные.»
else
# иначе — создать файл и сделать в нем новую запись
echo «Файл не существует, поэтому создается.»
echo «Создание нового файла» > $HOME/testing
fi
else
echo «Простите, но у вас нет Домашнего каталога»
fi
Пример работы кода:
Вначале команда test проверяет параметром -e, существует ли Домашний каталог пользователя, название которого хранится системой в переменной $HOME. При отрицательном результате скрипт завершит работу с выводом сообщения об этом. Если такой каталог обнаружен, параметр -е продолжает проверку. На этот раз ищет в $HOME файл testing. И если он есть, то в него дописывается информация, иначе он создастся, и в него запишется новая строка данных.
Проверка наличия файла
Проверка файла Bash на то, является ли данный объект файлом (то есть существует ли файл), выполняется с помощью параметра -f.
#!/bin/bash
if [ -f $HOME ]
then
echo «$HOME — это файл»
else
echo «$HOME — это не файл»
if [ -f $HOME/.bash_history ]
then
echo «А вот .bash_history — файл»
fi
fi
Пример работы кода:
В сценарии проверяется, является ли $HOME файлом. Результат проверки отрицательный, после чего проверяется настоящий файл .bash_history, что уже возвращает истину.
На заметку: на практике предпочтительнее использовать сначала проверку на наличие объекта как такового, а затем — на его конкретный тип. Так можно избежать различных ошибок или неожиданных результатов работы программы.
Проверка файла на пустоту
Чтобы определить, является ли файл пустым, нужно выполнить проверку с помощью параметра -s. Это особенно важно, когда файл намечен на удаление. Здесь нужно быть очень внимательным к результатам, так как успешное выполнение этого параметра указывает на наличие данных.
#!/bin/bash
file=t15test
touch $file
if [ -s $file ]
then
echo «Файл $file содержит данные.»
else
echo «Файл $file пустой.»
fi
echo «Запись данных в $file. »
date > $file
if [ -s $file ]
then
echo «Файл $file содержит данные.»
else
echo «Файл $file все еще пустой.»
fi
Результат работы программы:
В этом скрипте файл создаётся командой touch, и при первой проверке на пустоту возвращается отрицательный результат. Затем в него записываются данные в виде команды date, после чего повторная проверка файла возвращает истину.
Выводы
В статье была рассмотрена проверка существования файла bash, а также его пустоты. Обе функции дополняют друг друга, поэтому использовать их в связке — эффективный приём.
Хороший тон в написании сценариев командного интерпретатора — сначала определить тип файла и его дальнейшую роль в программе, а затем уже проверять объект на существование.
Источник
Linux error file exists
Бывает так, что при настройке сети в Linux, например при добавлении дополнительного IP-адреса для сетевого интерфейса, может появиться следующая ошибка:
# ip addr add 192.168.1.95/24 dev enp5s0
RTNETLINK answers: File exists
Традиционно, текст ошибки указывает совершенно не на ту проблему, которая возникла на самом деле. При возникновении данной ошибки обычно рекомендуют перезагрузить компьютер или полностью сбросить конфигурацию сетевого интерфейса через команды:
# ip addr flush dev enp5s0
# ip route flush dev enp5s0
Предполагается, что некий загадочный конфигурирующий файл или файл устройства освободится и можно будет произвести настройку.
Так вот, этого делать не нужно. Лучше посмотреть на исходную команду, и понять, что в ней может быть не так. Вроде бы все в порядке? Да! Но что если посмотреть на выхлоп:
link/ether . brd ff:ff:ff:ff:ff:ff
inet 192.168.1.95/24 brd 192.168.1.255 scope global enp5s0
valid_lft forever preferred_lft forever
Оказывается, такой IP с такой маской уже существует. По запарке можно было этого и не заметить. То есть, проблема оказалась в неправильном применении команды.
По непроверенной информации, RTNETLINK расшифровывается как ROUTE NETWORK LINK (иногда используется наименование NETLINK_ROUTE ), и под этим «объектом» подразумевается сокет маршрутизации IPv4. Соответственно, если сокет уже существует, а пользователь пытается своей командой косвенно создать такой же сокет, то будет появляеться вышеуказанная ошибка. Так же, подобная ошибка будет появляться, если есть какие-то неполадки в настройках маршрутизации.
Ждем, когда команда ip станет более интеллектуальной, и будет точно говорить в чем проблема, чтобы можно было ее быстро решить.
Источник
No such file or directory? But the file exists!
I’ve downloaded a game (Shank) but the bin file doesn’t run. The error that is shown when I try to launch the executable is:
8 Answers 8
You’re probably trying to run a 32-bit binary on a 64-bit system that doesn’t have 32-bit support installed.
There are three cases where you can get the message “No such file or directory”:
- The file doesn’t exist. I presume you’ve checked that the file does exist (perhaps because the shell completes it).
- There is a file by that name, but it’s a dangling symbolic link.
- The file exists, and you can even read it (for example, the command file shank-linux-120720110-1-bin displays something like “ELF 32-bit LSB executable …”), and yet when you try to execute it you’re told that the file doesn’t exist.
The error message in this last case is admittedly confusing. What it’s telling you is that a key component of the runtime environment necessary to run the program is missing. Unfortunately, the channel through which the error is reported only has room for the error code and not for this extra information that it’s really the runtime environment that’s to blame. If you want the technical version of this explanation, read Getting “Not found” message when running a 32-bit binary on a 64-bit system.
The file command will tell you just what this binary is. With a few exceptions, you can only run a binary for the processor architecture that your release of Ubuntu is for. The main exception is that you can run 32-bit (x86, a.k.a. IA32) binaries on 64-bit (amd64, a.k.a. x86_64) systems.
In Ubuntu up to 11.04, to run a 32-bit binary on a 64-bit installation, you need to install the ia32-libs package . You may need to install additional libraries (you’ll get an explicit error message if you do).
Since 11.10 (oneiric) introduced multiarch support, you can still install ia32-libs , but you can choose a finer-grained approach, it’s enough to get libc6-i386 (plus any other necessary library).
Источник
How do I tell if a regular file does not exist in Bash?
I’ve used the following script to see if a file exists:
What’s the correct syntax to use if I only want to check if the file does not exist?
20 Answers 20
The test command ( [ here) has a «not» logical operator which is the exclamation point (similar to many other languages). Try this:
Bash File Testing
-b filename — Block special file
-c filename — Special character file
-d directoryname — Check for directory Existence
-e filename — Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename — Check for regular file existence not a directory
-G filename — Check if file exists and is owned by effective group ID
-G filename set-group-id — True if file exists and is set-group-id
-k filename — Sticky bit
-L filename — Symbolic link
-O filename — True if file exists and is owned by the effective user id
-r filename — Check if file is a readable
-S filename — Check if file is socket
-s filename — Check if file is nonzero size
-u filename — Check if file set-user-id bit is set
-w filename — Check if file is writable
-x filename — Check if file is executable
How to use:
A test expression can be negated by using the ! operator
You can negate an expression with «!»:
The relevant man page is man test or, equivalently, man [ — or help test or help [ for the built-in bash command.
Also, it’s possible that the file is a broken symbolic link, or a non-regular file, like e.g. a socket, device or fifo. For example, to add a check for broken symlinks:
It’s worth mentioning that if you need to execute a single command you can abbreviate
I prefer to do the following one-liner, in POSIX shell compatible format:
For a couple of commands, like I would do in a script:
Once I started doing this, I rarely use the fully typed syntax anymore!!
To test file existence, the parameter can be any one of the following:
All the tests below apply to regular files, directories, and symlinks:
You can do this:
If you want to check for file and folder both, then use -e option instead of -f . -e returns true for regular files, directories, socket, character special files, block special files etc.
You should be careful about running test for an unquoted variable, because it might produce unexpected results:
The recommendation is usually to have the tested variable surrounded by double quotation marks:
the [ command does a stat() (not lstat() ) system call on the path stored in $file and returns true if that system call succeeds and the type of the file as returned by stat() is «regular«.
So if [ -f «$file» ] returns true, you can tell the file does exist and is a regular file or a symlink eventually resolving to a regular file (or at least it was at the time of the stat() ).
However if it returns false (or if [ ! -f «$file» ] or ! [ -f «$file» ] return true), there are many different possibilities:
- the file doesn’t exist
- the file exists but is not a regular file (could be a device, fifo, directory, socket. )
- the file exists but you don’t have search permission to the parent directory
- the file exists but that path to access it is too long
- the file is a symlink to a regular file, but you don’t have search permission to some of the directories involved in the resolution of the symlink.
- . any other reason why the stat() system call may fail.
In short, it should be:
To know for sure that the file doesn’t exist, we’d need the stat() system call to return with an error code of ENOENT ( ENOTDIR tells us one of the path components is not a directory is another case where we can tell the file doesn’t exist by that path). Unfortunately the [ command doesn’t let us know that. It will return false whether the error code is ENOENT, EACCESS (permission denied), ENAMETOOLONG or anything else.
The [ -e «$file» ] test can also be done with ls -Ld — «$file» > /dev/null . In that case, ls will tell you why the stat() failed, though the information can’t easily be used programmatically:
At least ls tells me it’s not because the file doesn’t exist that it fails. It’s because it can’t tell whether the file exists or not. The [ command just ignored the problem.
With the zsh shell, you can query the error code with the $ERRNO special variable after the failing [ command, and decode that number using the $errnos special array in the zsh/system module:
Источник