Ubuntu get linux source

Ubuntu Documentation

This page describes how to manage software repositories from the command line. (GUI tools are also available: Managing Repositories in Ubuntu or Kubuntu).

If you are using a minimal install or server install you will need to be familiar with a terminal based text editor like nano. If you are using a GUI install you can use Nano or GEdit.

The Basics

Ubuntu uses apt for package management. Apt stores a list of repositories or software channels in the file

and in any file with the suffix .list under the directory

See man sources.list for more about this storage mechanism.

By editing these files from the command line, we can add, remove, or temporarily disable software repositories.

Note: It’s always a good idea to backup a configuration file like sources.list before you edit it. To do so, issue the following command:

Typically, the beginning of the file /etc/apt/sources.list looks like this:

Explanation of the Repository Format

    All the lines beginning with one or two hashes (#) are comments, for information only.

The lines without hashes are apt repository lines. Here’s what they say:

deb: These repositories contain binaries or precompiled packages. These repositories are required for most users.

deb-src: These repositories contain the source code of the packages. Useful for developers.

http://archive.ubuntu.com/ubuntu: The URI (Uniform Resource Identifier), in this case a location on the internet. See the official mirror list or the self-maintained mirror list to find other mirrors.

saucy is the release name or version of your distribution.

main & restricted are the section names or components. There can be several section names, separated by spaces.

Other Versions

For other Ubuntu releases you would replace the ‘saucy’ with the current version you have installed (‘precise’, ‘quantal’, ‘raring’, ‘saucy’, ‘trusty’, . ) Type lsb_release -sc to find out your release.

Adding Repositories

Adding the Universe and Multiverse Repositories

Additional software repositories such as Universe and Multiverse can be enabled by uncommenting the corresponding apt lines (i.e. delete the ‘#’ at the beginning of the line). For Universe, uncomment those lines:

There are four similar lines for ‘multiverse’.

OR you may use the add-apt-repository command. If your release is ‘saucy’:

Depending on your location, you should replace ‘us.’ by another country code, referring to a mirror server in your region. Check sources.list to see what is used!

Type lsb_release -sc to find out your release. You may repeat the commands with «deb-src» instead of «deb» in order to install the source files.

Don’t forget to retrieve the updated package lists:

Adding Partner Repositories

You can add the partner repositories by uncommenting the following lines in your /etc/apt/sources.list file:

Читайте также:  Creative x fi xtreme audio sb0790 драйвер windows 10

Then update as before:

Be aware that the software contained within this repository is NOT open source.

Adding Other Repositories

There are some reasons for which you might want to add non-Ubuntu repositories to your list of software sources. Caution: To avoid trouble with your sytem, only add repositories that are trustworthy and that are known to work on Ubuntu systems!

You can add custom software repositories by adding the apt repository line of your software source to the end of the sources.list file. It should look something like this:

  • Don’t forget to make apt aware of your changes:
  • Adding Launchpad PPA Repositories

    Adding Launchpad PPA (Personal Package Archive) is possible conveniently via the command: add-apt-repository. This command is similar to «addrepo» on Debian.

    The command updates your sources.list file or adds/edits files under sources.list.d/. Type man add-apt-repository for detailed help.
    If a public key is required and available it is automatically downloaded and registered.

    Should be installed by default. On older or minimal Ubuntu releases, you may have to install software-properties-common and/or python-software-properties first (sudo apt-get install python-software-properties)

    Example: sudo add-apt-repository ppa:nhandler/ppa

    Enabling Repositories with a (non-interactive) Script

    This section seemed obsolete due to the add-apt-repository command, thus it has been removed.

    Suggestions & Recommendations

    It is always a good idea to back up configuration files like /etc/apt/sources.list before you begin editing. You can then revert your changes if needed.

    If you decide to add other repositories to sources.list, make sure that the repository is meant to work (and known to work) with Ubuntu. Repositories that are not designed to work with your version of Ubuntu can introduce inconsistencies in your system and might force you to re-install. Also, make sure that you really need to add external repositories as the software package(s) you are looking for may already have been introduced into the official repositories!

    Please keep in mind that it may not be legal (typically because of export restrictions) to enable some non-Ubuntu software repositories in some countries.

    You may be asked enter a security key when adding a non-Ubuntu repository to your sources. See Managing Authentication Keys for instructions.

    Источник

    How to get source code of package using the apt command on Debian or Ubuntu

    Table of contents

    How to get source code of package using the apt-get/apt command

    The procedure to download source code is as follows for Ubuntu Linux.

    Please note that apt-get does support third-party closed-source applications. You can only download the source code of open-source software.

    Step 1 – Enable source code repo

    Sources are normally not installed. Hence, you can only install them if you know the package name and when you enable them. Therefore, edit the /etc/apt/sources.list file, run:
    $ sudo vi /etc/apt/sources.list
    Make sure the deb-src type references an Ubuntu distribution’s source code as follows:
    # Sources specification for the Ubuntu 20.04 LTS distro #
    deb-src http://archive.ubuntu.com/ubuntu focal main restricted universe multiverse
    deb-src http://archive.ubuntu.com/ubuntu focal-updates main restricted universe multiverse
    deb-src http://security.ubuntu.com/ubuntu focal-security main restricted universe multiverse
    Where,

    1. deb-src : Indicate that you need source code for .DEB files.
    2. http://archive.ubuntu.com/ubuntu : URL to fetch index and .deb files source code.
    3. focal : Ubuntu Linux 20.04 LTS code name
    4. main restricted universe multiverse : State component name for repo such as main, restricted, universe, and multiverse

    Step 2 – Update index

    Run the following command to resynchronize the package index files from their sources as defined by the deb-src keyword in /etc/apt/sources.list for Ubuntu Linux
    $ sudo apt-get update
    # OR #
    $ sudo apt update

    Step 3 – Download Ubuntu package’s source code

    Let us download source code for bash shell, run:
    $ sudo apt-get source $ sudo apt-get source bash

    You may see the following error if you forgot to set up deb-src as explained in step # 1:

    E: You must put some ‘source’ URIs in your sources.list

    Step 4 – Understanding downloaded source code files

    Let us run the ls command to see source code:
    $ ls -l

    By default, the source code is extracted into bash-5.0 directory:
    $ cd bash-5.0
    $ ls
    The upstream bash source tarball with .tar.xz ending is stored in bash_5.0.orig.tar.xz file. A description file with .dsc ending contains the name of the package, both, in its filename as well as content (after the Source: keyword). A tarball, with any changes made to upstream source, plus all the files created for the Debian package stored in bash_5.0-6ubuntu1.1.debian.tar.xz file. If the —download-only option passed to the apt-get command, then the source package will not be unpacked:
    $ sudo apt-get —download-only source source bash
    When downloaded, we can extract the source files for bash as follows:
    $ dpkg-source -x /path/to/pkg.dsc
    $ dpkg-source -x bash_5.0-6ubuntu1.1.dsc
    It is also possible to build packages:
    $ sudo apt-get —build source $ sudo apt-get —build source bash
    Another option is to make changes in debian/rules files
    $ vi bash-5.0/debian/rules
    Next we can build out custom bash package as follows:
    $ export EDITOR=vim
    $ dch -n
    Make sure we satisfy the build dependencies for a source package and to avoid errors install those libs and tools:
    $ sudo apt-get -y build-dep bash
    Finally, build a Debian package:
    $ debuild
    Verify new packages:
    $ cd ..
    $ ls *.deb
    Install them:
    $ sudo dpkg -i bash_*.deb

    • 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

    How to download Debian package’s source code

    The procedure is the same as Ubuntu distro but URL syntax changes as follows:
    $ sudo vi /etc/apt/sources.list
    Edit/update as follows:
    # source repo for Debian 10 buster #
    deb-src deb http://deb.debian.org/debian buster main
    Save and close the file in vim, and then run the following command:
    $ sudo apt-get update
    Let us download source code for the Apache web server:
    $ apt-get source apache2

    Conclusion

    We explained how to enable Ubuntu/Debian source repo and download source code for the package by name. The apt-get source command is useful when you want to study packaging or a specific Debian package. Also useful to know which compile-time options enabled for a particular package. And finally, we can rebuild packages to add or remove components. See Debian guide wiki page for more information and read the following man pages by typing the man command:
    $ man apt
    $ man apt-get
    $ man 5 sources.list
    $ man debuild
    $ man dch

    🐧 Get the latest tutorials on Linux, Open Source & DevOps via

    Источник

    Команда source в Linux

    Командная оболочка играет очень важную роль в работе семейства операционных систем Linux. Она используется не только пользователями для работы в терминале, но и программами, а также компонентами операционной системы для обмена данными между собой. Для этого применяются переменные окружения. Для перезагрузки переменных окружения из файла часто используется команда source.

    Эта команда позволяет выполнить скрипт в текущем процессе оболочки bash. По умолчанию для выполнения каждого скрипта запускается отдельная оболочка bash, хранящая все его переменные и функции. После завершения скрипта всё это удаляется вместе с оболочкой. Команда source позволяет выполнить скрипт в текущем командном интерпретаторе, а это значит, что всё переменные и функции, добавленные в этом скрипте, будут доступны также и в оболочке после его завершения. Как вы уже поняли, в этой статье будет рассмотрена команда source linux.

    Команда source linux

    Синтаксис команды очень прост. Надо вызвать саму команду и передать ей путь к исполняемому файлу:

    $ source путь_к_файлу аргументы

    Никаких опций более не нужно. Если указан не абсолютный путь к файлу, а просто имя файла, то утилита будет искать исполняемый файл в текущей папке и директориях, указанных в переменной PATH. Давайте разберём несколько примеров работы с утилитой. Создаём скрипт, объявляющий переменную:

    Затем загрузим переменную из этого файла:

    Теперь можно попытаться вывести содержимое переменной и убедиться, что всё работает:

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

    Если выполняемому скрипту нужно передать параметры, можно это сделать, просто перечислив их после пути к файлу скрипта. Модифицируем наш скрипт, чтобы переменная бралась из первого параметра:

    И снова выполняем:

    source losstsource losst.ru

    Аналогично работают и функции. Если объявить функцию в скрипте bash, а затем выполнить его с помощью команды source linux, то функция станет доступна в интерпретаторе:

    #!/bin/bash
    print_site() <
    echo «losst.ru»
    >

    Теперь можно выполнить функцию print_site в терминале или любом другом скрипте:

    Для тех, кто знаком с программированием на языке Си, можно провести аналогию с директивой #include, делающей доступными в текущем файле функции из других файлов. Если файл, имя которого передано как параметр команде, не существует, она вернёт код возврата 1 и завершится:

    Вместо команды source можно использовать точку (.), однако здесь следует быть осторожными — между точкой и именем файла должен быть пробел для того, чтобы bash интерпретировал эту точку как отдельную команду, а не как часть имени файла:

    Однако, нельзя писать .losstsource или ./losstsource, потому что обозначение ./ — это уже отсылка на текущую директорию, скрипт будет выполнен как обычно.

    Выводы

    В этой небольшой статье мы рассмотрели работу с командой source linux. Как видите, это очень простая и в то же время полезная команда, очень сильно облегчающая работу в терминале. Именно с её помощью работают виртуальные окружения Python и многие другие подсистемы.

    Источник

    Читайте также:  Amd high definition audio device драйвер windows 10 x64 не видит наушники
    Оцените статью

    Ubuntu get linux source

    Ubuntu Documentation

    This page describes how to manage software repositories from the command line. (GUI tools are also available: Managing Repositories in Ubuntu or Kubuntu).

    If you are using a minimal install or server install you will need to be familiar with a terminal based text editor like nano. If you are using a GUI install you can use Nano or GEdit.

    The Basics

    Ubuntu uses apt for package management. Apt stores a list of repositories or software channels in the file

    and in any file with the suffix .list under the directory

    See man sources.list for more about this storage mechanism.

    By editing these files from the command line, we can add, remove, or temporarily disable software repositories.

    Note: It’s always a good idea to backup a configuration file like sources.list before you edit it. To do so, issue the following command:

    Typically, the beginning of the file /etc/apt/sources.list looks like this:

    Explanation of the Repository Format

      All the lines beginning with one or two hashes (#) are comments, for information only.

    The lines without hashes are apt repository lines. Here’s what they say:

    deb: These repositories contain binaries or precompiled packages. These repositories are required for most users.

    deb-src: These repositories contain the source code of the packages. Useful for developers.

    http://archive.ubuntu.com/ubuntu: The URI (Uniform Resource Identifier), in this case a location on the internet. See the official mirror list or the self-maintained mirror list to find other mirrors.

    saucy is the release name or version of your distribution.

    main & restricted are the section names or components. There can be several section names, separated by spaces.

    Other Versions

    For other Ubuntu releases you would replace the ‘saucy’ with the current version you have installed (‘precise’, ‘quantal’, ‘raring’, ‘saucy’, ‘trusty’, . ) Type lsb_release -sc to find out your release.

    Adding Repositories

    Adding the Universe and Multiverse Repositories

    Additional software repositories such as Universe and Multiverse can be enabled by uncommenting the corresponding apt lines (i.e. delete the ‘#’ at the beginning of the line). For Universe, uncomment those lines:

    There are four similar lines for ‘multiverse’.

    OR you may use the add-apt-repository command. If your release is ‘saucy’:

    Depending on your location, you should replace ‘us.’ by another country code, referring to a mirror server in your region. Check sources.list to see what is used!

    Type lsb_release -sc to find out your release. You may repeat the commands with «deb-src» instead of «deb» in order to install the source files.

    Don’t forget to retrieve the updated package lists:

    Adding Partner Repositories

    You can add the partner repositories by uncommenting the following lines in your /etc/apt/sources.list file:

    Читайте также:  Amd high definition audio device драйвер windows 10 x64 не видит наушники

    Then update as before:

    Be aware that the software contained within this repository is NOT open source.

    Adding Other Repositories

    There are some reasons for which you might want to add non-Ubuntu repositories to your list of software sources. Caution: To avoid trouble with your sytem, only add repositories that are trustworthy and that are known to work on Ubuntu systems!

    You can add custom software repositories by adding the apt repository line of your software source to the end of the sources.list file. It should look something like this:

  • Don’t forget to make apt aware of your changes:
  • Adding Launchpad PPA Repositories

    Adding Launchpad PPA (Personal Package Archive) is possible conveniently via the command: add-apt-repository. This command is similar to «addrepo» on Debian.

    The command updates your sources.list file or adds/edits files under sources.list.d/. Type man add-apt-repository for detailed help.
    If a public key is required and available it is automatically downloaded and registered.

    Should be installed by default. On older or minimal Ubuntu releases, you may have to install software-properties-common and/or python-software-properties first (sudo apt-get install python-software-properties)

    Example: sudo add-apt-repository ppa:nhandler/ppa

    Enabling Repositories with a (non-interactive) Script

    This section seemed obsolete due to the add-apt-repository command, thus it has been removed.

    Suggestions & Recommendations

    It is always a good idea to back up configuration files like /etc/apt/sources.list before you begin editing. You can then revert your changes if needed.

    If you decide to add other repositories to sources.list, make sure that the repository is meant to work (and known to work) with Ubuntu. Repositories that are not designed to work with your version of Ubuntu can introduce inconsistencies in your system and might force you to re-install. Also, make sure that you really need to add external repositories as the software package(s) you are looking for may already have been introduced into the official repositories!

    Please keep in mind that it may not be legal (typically because of export restrictions) to enable some non-Ubuntu software repositories in some countries.

    You may be asked enter a security key when adding a non-Ubuntu repository to your sources. See Managing Authentication Keys for instructions.

    Источник

    How to get source code of package using the apt command on Debian or Ubuntu

    Tutorial requirements
    Requirements Ubuntu or Debian Linux
    Root privileges Yes
    Difficulty Easy
    Est. reading time 5m

    Table of contents

    How to get source code of package using the apt-get/apt command

    The procedure to download source code is as follows for Ubuntu Linux.

    Please note that apt-get does support third-party closed-source applications. You can only download the source code of open-source software.

    Step 1 – Enable source code repo

    Sources are normally not installed. Hence, you can only install them if you know the package name and when you enable them. Therefore, edit the /etc/apt/sources.list file, run:
    $ sudo vi /etc/apt/sources.list
    Make sure the deb-src type references an Ubuntu distribution’s source code as follows:
    # Sources specification for the Ubuntu 20.04 LTS distro #
    deb-src http://archive.ubuntu.com/ubuntu focal main restricted universe multiverse
    deb-src http://archive.ubuntu.com/ubuntu focal-updates main restricted universe multiverse
    deb-src http://security.ubuntu.com/ubuntu focal-security main restricted universe multiverse
    Where,

    1. deb-src : Indicate that you need source code for .DEB files.
    2. http://archive.ubuntu.com/ubuntu : URL to fetch index and .deb files source code.
    3. focal : Ubuntu Linux 20.04 LTS code name
    4. main restricted universe multiverse : State component name for repo such as main, restricted, universe, and multiverse

    Step 2 – Update index

    Run the following command to resynchronize the package index files from their sources as defined by the deb-src keyword in /etc/apt/sources.list for Ubuntu Linux
    $ sudo apt-get update
    # OR #
    $ sudo apt update

    Step 3 – Download Ubuntu package’s source code

    Let us download source code for bash shell, run:
    $ sudo apt-get source $ sudo apt-get source bash

    You may see the following error if you forgot to set up deb-src as explained in step # 1:

    E: You must put some ‘source’ URIs in your sources.list

    Step 4 – Understanding downloaded source code files

    Let us run the ls command to see source code:
    $ ls -l

    By default, the source code is extracted into bash-5.0 directory:
    $ cd bash-5.0
    $ ls
    The upstream bash source tarball with .tar.xz ending is stored in bash_5.0.orig.tar.xz file. A description file with .dsc ending contains the name of the package, both, in its filename as well as content (after the Source: keyword). A tarball, with any changes made to upstream source, plus all the files created for the Debian package stored in bash_5.0-6ubuntu1.1.debian.tar.xz file. If the —download-only option passed to the apt-get command, then the source package will not be unpacked:
    $ sudo apt-get —download-only source source bash
    When downloaded, we can extract the source files for bash as follows:
    $ dpkg-source -x /path/to/pkg.dsc
    $ dpkg-source -x bash_5.0-6ubuntu1.1.dsc
    It is also possible to build packages:
    $ sudo apt-get —build source $ sudo apt-get —build source bash
    Another option is to make changes in debian/rules files
    $ vi bash-5.0/debian/rules
    Next we can build out custom bash package as follows:
    $ export EDITOR=vim
    $ dch -n
    Make sure we satisfy the build dependencies for a source package and to avoid errors install those libs and tools:
    $ sudo apt-get -y build-dep bash
    Finally, build a Debian package:
    $ debuild
    Verify new packages:
    $ cd ..
    $ ls *.deb
    Install them:
    $ sudo dpkg -i bash_*.deb

    • 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

    How to download Debian package’s source code

    The procedure is the same as Ubuntu distro but URL syntax changes as follows:
    $ sudo vi /etc/apt/sources.list
    Edit/update as follows:
    # source repo for Debian 10 buster #
    deb-src deb http://deb.debian.org/debian buster main
    Save and close the file in vim, and then run the following command:
    $ sudo apt-get update
    Let us download source code for the Apache web server:
    $ apt-get source apache2

    Conclusion

    We explained how to enable Ubuntu/Debian source repo and download source code for the package by name. The apt-get source command is useful when you want to study packaging or a specific Debian package. Also useful to know which compile-time options enabled for a particular package. And finally, we can rebuild packages to add or remove components. See Debian guide wiki page for more information and read the following man pages by typing the man command:
    $ man apt
    $ man apt-get
    $ man 5 sources.list
    $ man debuild
    $ man dch

    🐧 Get the latest tutorials on Linux, Open Source & DevOps via

    Источник

    Команда source в Linux

    Командная оболочка играет очень важную роль в работе семейства операционных систем Linux. Она используется не только пользователями для работы в терминале, но и программами, а также компонентами операционной системы для обмена данными между собой. Для этого применяются переменные окружения. Для перезагрузки переменных окружения из файла часто используется команда source.

    Эта команда позволяет выполнить скрипт в текущем процессе оболочки bash. По умолчанию для выполнения каждого скрипта запускается отдельная оболочка bash, хранящая все его переменные и функции. После завершения скрипта всё это удаляется вместе с оболочкой. Команда source позволяет выполнить скрипт в текущем командном интерпретаторе, а это значит, что всё переменные и функции, добавленные в этом скрипте, будут доступны также и в оболочке после его завершения. Как вы уже поняли, в этой статье будет рассмотрена команда source linux.

    Команда source linux

    Синтаксис команды очень прост. Надо вызвать саму команду и передать ей путь к исполняемому файлу:

    $ source путь_к_файлу аргументы

    Никаких опций более не нужно. Если указан не абсолютный путь к файлу, а просто имя файла, то утилита будет искать исполняемый файл в текущей папке и директориях, указанных в переменной PATH. Давайте разберём несколько примеров работы с утилитой. Создаём скрипт, объявляющий переменную:

    Затем загрузим переменную из этого файла:

    Теперь можно попытаться вывести содержимое переменной и убедиться, что всё работает:

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

    Если выполняемому скрипту нужно передать параметры, можно это сделать, просто перечислив их после пути к файлу скрипта. Модифицируем наш скрипт, чтобы переменная бралась из первого параметра:

    И снова выполняем:

    source losstsource losst.ru

    Аналогично работают и функции. Если объявить функцию в скрипте bash, а затем выполнить его с помощью команды source linux, то функция станет доступна в интерпретаторе:

    #!/bin/bash
    print_site() <
    echo «losst.ru»
    >

    Теперь можно выполнить функцию print_site в терминале или любом другом скрипте:

    Для тех, кто знаком с программированием на языке Си, можно провести аналогию с директивой #include, делающей доступными в текущем файле функции из других файлов. Если файл, имя которого передано как параметр команде, не существует, она вернёт код возврата 1 и завершится:

    Вместо команды source можно использовать точку (.), однако здесь следует быть осторожными — между точкой и именем файла должен быть пробел для того, чтобы bash интерпретировал эту точку как отдельную команду, а не как часть имени файла:

    Однако, нельзя писать .losstsource или ./losstsource, потому что обозначение ./ — это уже отсылка на текущую директорию, скрипт будет выполнен как обычно.

    Выводы

    В этой небольшой статье мы рассмотрели работу с командой source linux. Как видите, это очень простая и в то же время полезная команда, очень сильно облегчающая работу в терминале. Именно с её помощью работают виртуальные окружения Python и многие другие подсистемы.

    Источник

    Читайте также:  Computer restarts after windows
    Оцените статью
    Tutorial requirements
    Requirements Ubuntu or Debian Linux
    Root privileges Yes
    Difficulty Easy
    Est. reading time 5m