Linux show variable value

How to print / echo environment variables?

The expansion $NAME to empty string is done by the shell earlier, before running echo , so at the time the NAME variable is passed to the echo command’s environment, the expansion is already done (to null string).

To get the same result in one command:

Note that only the printenv -based command preserves the semantics of the OP’s command: defining NAME as a command-scoped environment variable, which only the invoked command and its child processes see, but no subsequent shell commands. The other commands do something very different: they define NAME as an until-the-current-shell-exits shell-only variable, which all subsequent shell commands see, but no external utilities.

To bring the existing answers together with an important clarification:

As stated, the problem with NAME=sam echo «$NAME» is that $NAME gets expanded by the current shell before assignment NAME=sam takes effect.

Solutions that preserve the original semantics (of the (ineffective) solution attempt NAME=sam echo «$NAME» ):

Use either eval [1] (as in the question itself), or printenv (as added by Aaron McDaid to heemayl’s answer), or bash -c (from Ljm Dullaart’s answer), in descending order of efficiency:

NAME=sam eval 'echo "$NAME"' # use `eval` only if you fully control the command string NAME=sam printenv NAME NAME=sam bash -c 'echo "$NAME"' 

printenv is not a POSIX utility, but it is available on both Linux and macOS/BSD.

What this style of invocation ( = cmd . ) does is to define NAME :

  • as an environment variable
  • that is only defined for the command being invoked.

In other words: NAME only exists for the command (child process) being invoked, and has no effect on the current shell (if no variable named NAME existed before, there will be none after; a preexisting NAME variable remains unchanged).

POSIX defines the rules for this kind of invocation in its Command Search and Execution chapter.

The following solutions work very differently (quoted from heemayl’s answer):

NAME=sam; echo "$NAME" NAME=sam && echo "$NAME" 

While they produce the same output, they instead define:

  • a shell variable NAME (only) rather than an environment variable
    • if echo were a command that relied on environment variable NAME , it wouldn’t be defined (or potentially defined differently from earlier).

    Note that every environment variable is also exposed as a shell variable, but the inverse is not true: shell variables are only visible to the current shell and its subshells, but not to child processes, such as external utilities and (non-sourced) scripts (unless shell variables are designated as environment variables (too) with export or declare -x ).

    [1] Technically, bash is in violation of POSIX here (as is zsh ): Since eval is a special shell built-in, the preceding NAME=sam assignment should cause the the variable $NAME to remain in scope after the command finishes, but that’s not what happens.
    However, when you run bash in POSIX compatibility mode, it is compliant.
    dash and ksh are always compliant.
    The exact rules are complicated, and some aspects are left up to the implementations to decide; again, see Command Search and Execution.
    Also, the usual disclaimer applies: Use eval only on input you fully control or implicitly trust.

    Источник

    Как вывести значения всех переменных и переменных окружения в Linux

    Как перечислить все имена переменных и их текущие значения? Как показать только переменные окружения? Ответу на эти вопросы посвящена данная статья.

    Можно вывести значения переменных по одной, например:

    echo $HOME echo $PWD echo $USER echo $SHELL

    Если вам нужен полный список, то продолжайте читать.

    printenv

    Для bash: (стандартная оболочка во многих дистрибутивах Linux)

    Введите следующую команду в терминале, чтобы распечатать все переменные среды:

    Для получения дополнительной информации об этой команде прочтите справочную страницу:

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

    Это покажет вам не только переменные оболочки, но и переменные среды.

    Для zsh: (оболочка по умолчанию используется в Kali Linux)

    Используйте следующую команду:

    ( setopt posixbuiltin; set; ) | less

    Для получения дополнительной информации о параметрах ZSH смотрите справочную страницу

    declare

    Вы можете увидеть все переменные с помощью встроенной команды declare.

    Если вас интересуют только переменные среды, используйте

    Запустите «help declare», чтобы увидеть, какие есть другие опции.

    Переменные среды, доступные для запуска приложения

    Во всех описанных выше методах предлагается следующая процедура:

    • запустить терминал
    • показать переменные среды, используя env, printenv или что-то ещё

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

    Это заметно, если, например, вы используете свой ~/.profile, или .bashrc, или .zshenv (в зависимости от вашей оболочки) для изменения переменных среды — как классическое добавление каталогов к PATH.

    Чтобы увидеть переменные среды, доступные для приложения, запущенного непосредственно в графической среде, вы можете сделать следующее (в Gnome Shell, я уверен, что есть эквивалентный метод во всех других DE):

    xterm -e bash --noprofile --norc

    Или, если у вас нет xterm, то запустите:

    gnome-terminal - bash --noprofile --norc

    Теперь у вас есть терминал с оболочкой, которая не добавляла никаких переменных среды. Вы можете использовать env здесь, чтобы перечислить все свои переменные среды:

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

    Связанные статьи:

    Источник

    How to Print Environment Variables in Linux

    Wondering what environment variables are set on your current shell? Learn how to print environment variables in Linux.

    Environment variables are specific to certain environments. A generic answer, right?

    But really, those are the variables that are just specific to your current system environment such as the currently logged-in user will be stored inside the «USER» variable.

    Still confused? no worries. I will walk you through a brief understanding of environment variables and then jump to various ways to print them.

    What are Environment Variables?

    Nope, it’s not related to your Desktop Environment.

    One of the most basic environment variables that you encounter on a daily basis is Hostname. So have you ever wondered why it’s always written in all caps?

    Because most of the environment variables are pre-defined by the system and are global variables so you’ll encounter them often written in all caps.

    So why use environment variables in the first place?

    Suppose you are a programmer and your code needs to have access to your database key which should never be shared in public.

    So what options do you have while sharing the entire code on Git? Wrap the database key to the environment variable.

    This way you can set instructions on Git as «if you want to make this code work, interchange this variable with your database key.»

    Of course, this was the one way of using environment variables. So let’s have a look at some common environment variables in Linux.

    Environment Variable Description
    HOME Shows home directory for the current user
    HOSTNAME Contains Hostname of your system
    UID Stores unique ID of the user
    SHELL Shows the path to the shell which is being used currently
    BASH_VERSION Contains version currently used bash instance
    HISTFILE Path of the file where the history of commands is saved
    TERM Shows the type of log-in terminal you’re using
    PATH Shows path of commands and directories are separated by columns

    There are various ways through which you can print environment variables in Linux and I’ll try to cover each of them. So let’s start with the easiest one.

    Using printenev Command

    The printenv utility is used to print environment variables for the current shell.

    Suppose I want to print the value of USERNAME using printenv so my command will be as follows:

    Use printenv to print environment variable

    Similarly, you can also use the printenv utility to print more than one environment variable by separating them with .

    So how about printing the value of HOME and USERNAME at once using printenv?

    First, it’ll print the home directory of the currently logged-in user and in the second line, the hostname will be there.

    Use printenv to print HOME and HOSTNAME

    But what if you are looking for a way by which you can print each environment variable available in the current shell?

    You can easily accomplish this by executing the printenv command without any options or arguments whatsoever.

    Using echo Command

    If you’ve been using Linux for a while, the chances of using this method to print environment variables are quite high (even if you were unaware that it’s not an environment variable).

    Now, let me show you how you’re supposed to print the value of USERNAME with echo:

    Print environment variable using echo command

    But what if you want to print multiple environment variables using echo? just follow the given syntax:

    So how about printing values of HOME, USERNAME, and HOSTNAME all at once using echo?

    echo -e "$USERNAME \n$HOME \n$HOSTNAME"

    Use echo command to print multiple values of environment variables

    Using env Command

    The env command is generally used by shell scripts to launch the correct interpreter but you can also use the env command to list available environment variables.

    The env command if applied without any arguments and options, will print all the available environment variables.

    Use env command to print environemnt variable

    But what if you want to get the value of a specific environment variable? you can easily filter results with the grep command.

    For demonstration, I’ll be printing out the value of HOME with the echo command:

    Use env command to print environment variable

    Using declare Command

    The declare command is used to declare and print the value of variables in the shell.

    Like any other example shown above, you can use declare without any argument and will bring the list of available variables.

    Use declare command to print environment variables

    Previously, I showed you how you can use the grep command to filter results but what if you want to filter more than one result?

    First, let’s have a look at the syntax for filtering multiple environment variables:

    For example, let’s print the value of HOSTNAME and USERNAME:

    declare | grep 'HOSTNAME\|USERNAME'

    Use grep with declare to print multiple environment variables

    Using set Command

    Generally, the set command is used to set and unset flags in the shell so that you determine the exact behavior for the upcoming process.

    But you can also use the set command to print environment variables for the current shell.

    To print each environment variable, use the given command:

    Use set command to print environment variables

    You can use the same approach used in the above method to filter results from the set command.

    But still, let’s look at a simple example using the grep command to print multiple environment variables.

    set | grep 'HISTFILESIZE\|HISTFILE\|GNOME_SHELL_SESSION_MODE'

    Use set commad to print specific environment variables

    Wrapping up

    Though there are various methods for printing environment variables, I’d highly suggest you use the first method the syntax is the least complicated in terms of filtering specific variables.

    And if you are still confused, the comments section is open to you.

    Источник

    Читайте также:  Полное удаление virtualbox linux
Оцените статью
Adblock
detector