How to change locale linux

Содержание
  1. How to Change or Set System Locales in Linux
  2. How to View System Locale in Linux
  3. How to Set System Locale in Linux
  4. If You Appreciate What We Do Here On TecMint, You Should Consider:
  5. Locale (Русский)
  6. Contents
  7. Генерирование локалей
  8. Установка локали
  9. Установка системной локали
  10. Переопределение системной локали в пользовательском сеансе
  11. Немедленное применение изменений локали
  12. Дополнительно
  13. Переменные окружения
  14. LANG: локаль по умолчанию
  15. LANGUAGE: запасные локали
  16. LC_TIME: формат даты и времени
  17. LC_COLLATE: порядок сортировки
  18. LC_ALL: решение проблем
  19. Советы и рекомендации
  20. Запуск приложения с другой локалью в терминале
  21. Запуск приложения с другой локалью из меню
  22. Решение проблем
  23. Эмулятор терминала не поддерживает UTF-8
  24. gnome-terminal или rxvt-unicode не поддерживают UTF-8
  25. Моя система использует неверный язык
  26. Linux: Define Locale and Language Settings
  27. Locale and Language Settings
  28. Add New Locale
  29. Ubuntu-18.04
  30. Ubuntu-14.04
  31. CentOS-7, CentOS-6
  32. Set Locale for the Current Session
  33. Define Locale and Language Permanently
  34. Set Default System Locale
  35. Ubuntu-18.04
  36. Ubuntu-14.04
  37. CentOS-7
  38. CentOS-6
  39. Andrew Beacock’s Blog
  40. Search This Blog
  41. How to change your default locale on Ubuntu Linux

How to Change or Set System Locales in Linux

A locale is a set of environmental variables that defines the language, country, and character encoding settings (or any other special variant preferences) for your applications and shell session on a Linux system. These environmental variables are used by system libraries and locale-aware applications on the system.

Locale affects things such as the time/date format, the first day of the week, numbers, currency and many other values formatted in accordance with the language or region/country you set on a Linux system.

In this article, we will show how to view your currently installed system locale and how to set system’s locale in Linux.

How to View System Locale in Linux

To view information about the current installed locale, use the locale or localectl utility.

You can view more information about an environmental variable, for example LC_TIME, which stores the time and date format.

To display a list of all available locales use the following command.

How to Set System Locale in Linux

If you want to change or set system local, use the update-locale program. The LANG variable allows you to set the locale for the entire system.

The following command sets LANG to en_IN.UTF-8 and removes definitions for LANGUAGE.

To configure a specific locale parameter, edit the appropriate variable. For instance.

You can find global locale settings in the following files:

  • /etc/default/locale – on Ubuntu/Debian
  • /etc/locale.conf – on CentOS/RHEL

These files can also be edited manually using any of your favorite command line editors such as Vim or Nano, to configure your system locale.

To set a global locale for single user, you can simply open

/.bash_profile file and add the following lines.

For more information, see the locale, update-locale and localectl man pages.

That’s all! In this short article, we have explained how to view and set system local in Linux. If you have any questions, use the feedback form below to reach us.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Читайте также:  Как распаковать windows инсталлятор героев 3 под mac os

Источник

Locale (Русский)

Локали определяют язык, который использует система, а также региональные особенности, такие как денежные знаки, формат чисел, даты и времени и наборы символов. Они используются glibc и некоторыми другими программами или библиотеками для рендеринга текста.

Contents

Генерирование локалей

Имена локалей обычно имеют вид [язык][_ТЕРРИТОРИЯ][.НАБОР_СИМВОЛОВ][@модификатор] , где язык это код языка ISO 639, ТЕРРИТОРИЯ это код страны ISO 3166 и НАБОР_СИМВОЛОВ это кодировка вроде ISO-8859-1 или UTF-8. Смотрите setlocale(3) .

Чтобы вывести список всех доступных и сгенерированных локалей, выполните:

Перед тем, как локаль сможет быть использована в системе, она должна быть сгенерирована. Локали, которые вы можете сгенерировать перечислены в файле /etc/locale.gen . Чтобы сгенерировать локаль, первым делом раскомментируйте соответствующую строку в файле (а для удаления наоборот, закомментируйте); вы можете раскомментировать несколько локалей, в зависимости от ваших потребностей.

Например, для русской локали раскомментируйте ru_RU.UTF-8 UTF-8 :

После сохранения файла сгенерируйте выбранные локали командой:

Установка локали

Чтобы отобразить текущую локаль и связанные с ней переменные окружения, наберите:

Используемая локаль, выбранная среди сгенерированных в системе, устанавливается в файлах locale.conf , каждый из которых должен содержать список переменных окружения в том же формате, в каком их выводит команда locale.

Чтобы посмотреть список доступных ранее сгенерированных локалей, выполните:

Также можно использовать localectl(1) :

Установка системной локали

  • Системная локаль устанавливается с помощью переменной LANG в файле /etc/locale.conf . Значением должен быть первый столбец из раскомментированной записи в /etc/locale.gen :

Вы можете установить ее также при помощи localectl:

Переопределение системной локали в пользовательском сеансе

  • Системная локаль может переопределяться в каждом пользовательском сеансе с помощью файла

/.config/locale.conf (или, в общем случае, $XDG_CONFIG_HOME/locale.conf либо $HOME/.config/locale.conf ).

Немедленное применение изменений локали

После внесения изменений в файлы locale.conf , они вступят в силу после перезагрузки системы, и для отдельных сеансов пользователей — при входе. Чтобы принудительно обновить локаль в текущем окружении без перезагрузки, выполните:

Дополнительно

Переменные окружения настроек локали могут также быть установлены обычным способом, как указано на странице переменные окружения.

Например, чтобы проверить, как работает конкретное приложение с какой-нибудь локалью, вы можете запустить его следующим образом:

Аналогично, для установки локали всем процессам, запускаемом из текущей командной оболочки (например, в процессе установки системы):

Переменные окружения

Файлы locale.conf могут содержать следующие переменные окружения:

Полное объяснение этих переменных можно узнать в locale(7) , детали описаны в locale(5) .

LANG: локаль по умолчанию

Локаль, установленная в этой переменной используется в качестве значения для всех остальных LC_* -переменных, которые не установлены явно.

LANGUAGE: запасные локали

Программы, использующие gettext для перевода, учитывают также переменную LANGUAGE в дополнение к стандартным переменным. Это позволяет пользователям установить список локалей, которые будут использоваться в указанном порядке для поиска перевода. Если перевод для более предпочтительной локали (которая идет первее в списке) недоступен, будет произведена попытка получить перевод для следующей, и так далее. Например, пользователь из Австралии может предпочесть британский вариант перевода американскому:

LC_TIME: формат даты и времени

Например, если переменная LC_TIME имеет значение en_US.UTF-8 , будет использован формат даты ММ/ДД/ГГГГ . Если вы хотите использовать формат ISO 8601 ( ГГГГ-ММ-ДД ), установите:

LC_COLLATE: порядок сортировки

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

Установка значения LC_COLLATE=C , например, приведет к тому, что команда ls будет располагать файлы, имена которых начинаются с точки, первыми, за ними последуют имена, начинающиеся с цифры, затем с заглавной и, наконец, со строчной буквы:

Чтобы избежать возможных проблем, в Arch переменная установлена как LC_COLLATE=C в /etc/profile , однако этот метод сейчас устарел.

LC_ALL: решение проблем

Переменная LC_ALL переопределяет своим значением все LC_* -переменные, включая LANG , независимо от того, установлены они или нет.

Читайте также:  Mac os mojave дистрибутив

Переменная LC_ALL — единственная из всех LC_ -переменных, которую нельзя установить в /etc/locale.conf : она предназначена только в целях проверки при решении проблем.

Советы и рекомендации

Запуск приложения с другой локалью в терминале

Например, чтобы запустить программу abiword на иврите:

Запуск приложения с другой локалью из меню

Скопируйте файл .desktop в домашний каталог пользователя:

И отредактируйте команду в опции Exec :

Решение проблем

Эмулятор терминала не поддерживает UTF-8

Небольшой список терминалов с поддержкой UTF-8:

  • gnustep-terminal
  • konsole
  • mlterm
  • rxvt-unicode (Русский)
  • st
  • эмуляторы на основе VTE
  • xterm — необходимо запускать с опцией -u8 или с настройкой xterm*utf8: 2 . Также вы можете запускать uxterm, который предоставляется пакетом xterm .

gnome-terminal или rxvt-unicode не поддерживают UTF-8

Чтобы заработала поддержка UTF-8 в этих приложениях, необходимо запускать их с локалью, в которой установлена кодировка UTF-8, например ru_RU.UTF-8 . Включите эту локаль в системе, установите ее как системную локаль по умолчанию в соответствиями с инструкциями в предыдущих разделах и перезагрузите компьютер.

Моя система использует неверный язык

Возможно, некоторые переменные окружения из locale.conf были переопределены каким-то другим файлом, например

/.pam_environment , который используется в GNOME. Подробнее смотрите на странице Переменные окружения#Установка переменных.

Если вы используете окружение рабочего стола, такое как GNOME, его настройки могут перекрывать locale.conf .

KDE Plasma также позволяет изменить язык интерфейса через свои настройки. Если он всё равно использует язык по умолчанию после изменения, удаление файла

/.config/plasma-locale-settings.sh ) должно помочь.

Если вы используете экранный менеджер вместе с accountsservice , смотрите Display manager (Русский)#Установка языка.

LightDM автоматически использует accountsservice для выбора локали, если он установлен. В противном случае LightDM читает настройки сеанса из

/.dmrc . Возможно, что нежелательные настройки локали прочитались оттуда.

Источник

Linux: Define Locale and Language Settings

Locales are used in Linux to define which language and character set (encoding) user see in the terminal.

From this article you will learn how to check and change the current locale and language settings from the command line in Linux.

I will show how to check the current locale and language settings and how to get the list of available locals.

You will also see how to set locale and language temporary for the current session only as well as permanently for a single user or for the all users (change default system locale).

Cool Tip: Determine and change a file’s character encoding from the command line in Linux! The best solution for converting text files between different charsets! Read more →

Locale and Language Settings

Execute locale command to get the information about the current locale and language settings:

To list all enabled locales, run:

Locale is defined in the following format:

LANGUAGE ISO 639 language code
TERRITORY ISO 3166 country code
CODESET Character set or encoding identifier, like ISO-8859-1 or UTF-8

e.g. Australian English with UTF-8 encoding is defined as: en_AU.UTF-8

Add New Locale

New locale: Before a locale can be enabled on the system, it must be generated.

If you didn’t find the desired language or encoding in the list of enabled locales, you can search for them in the list of all supported locales and install whatever you need.

Ubuntu-18.04

Supported releases: Ubuntu-15.04, 15.10, 16.04, 16.10, 18.04.

List the all supported (available for generation) locales:

Find the desired locale, for example:

Generate it with:

Now you should see it in the list of available locales:

Ubuntu-14.04

Supported releases: Ubuntu-9.10, 10.04, 10.10, 11.04, 11.10, 12.04, 12.10, 13.04, 13.10, 14.04, 14.10.

Читайте также:  Linux install new fonts

List the all supported (available for generation) locales:

Find the desired locale, for example:

Generate it with:

Now you should see it in the list of available locales:

CentOS-7, CentOS-6

List the all supported (available for generation) locales:

Find the desired locale, for example:

Generate it with:

Now you should see it in the list of available locales:

Set Locale for the Current Session

To set the required locale and language for the current session – it is just needed to redefine this variable.

Below you will find the examples of setting locales for some popular languages.

Set the environment variable LANG , as shown in the examples, to change a language and encoding for the current session:

Set the English locale:

Set the Russian locale:

Set the French locale:

Set the German locale:

Set the Hindi locale:

Define Locale and Language Permanently

For this you can set the required value of the LANG variable in a user’s bash profile and the needed locale and language settings will be automatically loaded upon the each session.

Put the following line to the

/.profile files, to change permanently the locale of the current user to en_US.utf8 :

By default, the modification will take effect after logout/login, but you can force it if you run one of the below commands, depending on in which file you have defined the LANG variable:

Set Default System Locale

Cool Tip: Create the awesome ASCII banners from the Linux command line and decorate your SSH warning messages! Read more →

Perform the following steps to permanently change the system locale (for the all users).

Ubuntu-18.04

Supported releases: Ubuntu-15.04, 15.10, 16.04, 16.10, 18.04.

Ubuntu-14.04

Supported releases: Ubuntu-9.10, 10.04, 10.10, 11.04, 11.10, 12.04, 12.10, 13.04, 13.10, 14.04, 14.10.

Edit the file with default locale settings:

Set the LANG variable:

CentOS-7

CentOS-6

Edit the file with default locale settings:

Set the LANG variable:

Reboot is required: Note that the above settings will take effect after reboot only.

Источник

Andrew Beacock’s Blog

eng mgr / leader / full stack / java / agile / tdd / security / aws / go

Search This Blog

How to change your default locale on Ubuntu Linux

One problem that has repeatedly cropped up when developing in Java is strange error messages in our unit tests for certain text manipulation tests when running on a freshly installed Ubuntu desktop.

They are all related to Ubuntu’s default British locale: en_GB.UTF-8

This was causing files checked out of CVS to be in Unicode (UTF-8) format rather than ISO-8859-1 and so the British pound sign (£) was being encoded as a double-byte (rather than single-byte) character in the file.

To check which locale you currently have as your default just run: locale

Changing the default locale is a little different on Ubuntu compared to most Linux distros, these are the steps we needed to go through to get it changed:

Add the locale to the list of ‘supported locales’
Edit /var/lib/locales/supported.d/local and add the following line:
en_GB ISO-8859-1

Regenerate the supported locales
Run sudo dpkg-reconfigure locales

Change the default locale
Edit /etc/environment and ensure the LANG and LANGUAGE lines read as follows:
LANG=»en_GB»
LANGUAGE=»en_GB:en»

UPDATE ’09: An old collegue has suggested that this change should now be made in /etc/default/locale rather than /etc/environment — Thanks Guy!

Rerun locale to check that your default locale is now en_GB

Источник

Оцените статью