What is setenv linux

Linux setenv command

On Unix-like operating systems running the C shell, the setenv built-in command adds, or changes, the value of an environment variable.

Syntax

Arguments

VAR The name of the variable to be set.
VALUE The value of the variable, as either a single word or a quoted string.

Description

setenv is a built-in function of the C shell (csh). It is used to define the value of environment variables.

If setenv is given no arguments, it displays all environment variables and their values. If only VAR is specified, it sets an environment variable of that name to an empty (null) value. If both VAR and VALUE are specified, it sets the variable named VAR to the value VALUE. setenv is similar to the set command, that also sets an environment variable’s value. However, unlike set, setenv also «exports» this environment variable to any subshells. In this way, it is the equivalent of the bash command export.

For instance, if you are inside the c shell, and you use setenv to set the following variable:

We can then use the echo command to view the value of that variable:

Our value, «myvalue«, was returned. Now let’s run bash as a subshell:

and see if it knows the value of our variable MYVAR:

As you can see, the value of MYVAR was passed on to bash.

Now, let’s see how set is different. Let’s go back to csh by exiting the bash subshell:

. and use set to set another environment variable, MYVAR2:

(The syntax of set, as you can see, is slightly different. It uses an equals sign to assign a value.) Now let’s check the value of MYVAR2:

And now let’s go back to bash:

. and check the value of MYVAR2:

This time, no value is reported, because the variable was not «exported» to the subshell. So, when you are using csh, if you want environment variables to remain local to only the current shell, use set. If you want them to carry over to subshells as well, use setenv.

Examples

Sets the environment variable PATH. PATH is a list of path names separated by colons («:«), which are the default paths to search for executable files when a command is called. After you set PATH to the above value, the shell looks in the paths /bin, /usr/bin, /usr/sbin, and /usr/local/bin, in that order, for the executable files of any subsequent commands you run.

csh — The C shell command interpreter.
ksh — The Korn shell command interpreter.
set — Set the value of shell options and positional parameters.
sh — The Bourne shell command interpreter.

Источник

setenv Command Tutorial To Add, Delete and Change Environment Variables In Linux

Linux and Unix ecosystem mainly used command line based. While working with command line and C Shell we generally need some values to use with commands. Shells provide environment variables for this. This environment variables can be managed with setenv command like add, change and remove.

Читайте также:  Jetbrains pycharm professional linux

Syntax

Syntax of setenv command is very simple we just need to provide the variable name and data

List All Environment Variables

We can use setenv in order to list all environment variables currently defined in C Shell.

List All Environment Variables

Add Environment Variable

We will start by creating come environment variable and setting some data to it. We can use lowercase or uppercase letters bu the general usage is uppercase letters. In this case we will create a variable named MYIP and set value 192.168.1.10

We can print specific environment variable with echo command. We will provide the environment variable and and prefix with $ . In this example we will print environment variable named MYIP like below.

Print Environment Variable

Pass Environment Variables To Sub or Child Shell

Linux process and shell architecture provides the ability to run sub process or shell. Sub process and shell will create a new environment. If we need to use current environment variables in the sub process or shell we just need to use them accordingly. For example in the following example we will print previously defined MYIP in the bash sub-shell.

Pass Environment Variables To Sub or Child Shell

Set OR Update One Environment Variable Value

After assigning a value to a environment variable we may need to update it with new value. We can use set command in order to update current environment variable with a new value. In this example we will update our variable MYIP with 192.168.1.20

Set OR Update One Environment Variable Value

Useful Environment Variables

There are a lot of default enviroment variables. Here are some of them.

Источник

putenv() and setenv()

How do you modify the environment in UNIX?

The Specifications

There are two functions available to set environment variables: putenv() and setenv(), plus a third function unsetenv() to remove values from the environment.

putenv takes a string of the form NAME=VALUE. This is reasonably convenient as it gets for adding a fixed value to the environment but less so if either of the name or value aren’t fixed. Also it does not copy the string, which has the following important implications:

  • You must not pass an auto array to it
  • If you modify the string, you modify the environment
  • After removing the name from the environment you can free the string and therefore not leak memory

setenv takes the name and value separately and allows you to back out of the variable is already set. This is adequately convenient for most possible applications. It creates a new copy, so:

  • You can pass an auto array
  • You can modify the values you passed without affecting the environment
  • You have no idea (in general) what, if anything, to free when you remove the value from the environment

The usage and rationale section states that (1) setenv is preferred and (2) putenv is the only way to avoid leaks. These two statements seem inconsistent, but there you go.

unsetenv is straightforward enough: it just removes a name from the environment.

Although presumably an implementation is free to magically know that it must free any copies that were made with setenv but not strings passed via putenv there is no guarantee given that it does so, so it must be assumed that memory is leaked by this function. For most applications this isn’t a big problem: they modify the environment rarely or never, or do so just before calling execve, making leaks short-lived.

Threads

None of these functions are required to be thread-safe (though some implementations do support such a guarantee). So be extremely cautious using them from multithreaded programs or from libraries. Using them from signal handlers is probably right out.

Читайте также:  Как убрать запрос пароля при вход windows

Implementation Variations

Linux

Some ancient versions of Linux putenv will copy the string. Also some ancient versions declare the argument as const char *; code written assuming this may fail to compile on more recent versions or different platforms.

FreeBSD and Mac OS X

putenv is documented as being equivalent to the obvious setenv call; i.e. it copies the string, in violation of the specification.

Solaris

Solaris has putenv but lacks setenv and unsetenv before 5.10 (AFAICT).

(Some versions of?) HPUX putenv declare the argument as const char *; code written assuming this may fail to compile on more recent versions or different platforms.

(Some versions of?) HPUX do not have setenv or unsetenv.

(Please feel free to contribute to this section.)

Conclusions

putenv is very widely available, but it might or might not copy its argument, risking memory leaks.

You can’t assume that setenv or unsetenv are universally available, though the situation does appear to be improved on modern platforms and setenv at least should not be hard to implement in terms of putenv.

If you do use setenv or unsetenv then memory leaks are very likely.

There is no completely portable way to remove something from the environment (the getenv() rationale says conforming applications may not modify the environment array directly, though I’ve not yet found this stated in a normative section.)

Avoid any kind of concurrency beteween these functions.

Источник

What is setenv linux

Раньше мы познакомились с тем, как получать параметры в программе с помощью семейства функций getopt (подробнее читайте «Шаг 10 — Передача опций в программу — getopt» и «Шаг 11 — Передача длинных опций в программу — getopt_long»). Но существует еще один метод — переменные окружения или переменные среды. С ними мы успели уже познакомиться раньше в шаге «Шаг 13 — Получение информации о пользователе». С помощью данных переменных можно передавать в программу дополнительные специфические параметры, которые могут использоваться несколькими программами одновременно и они характеризуют «среду», в которой выполняется программа.

Например, если Вы разрабатываете какую-то систему состоящую из нескольких программ работающих независимо, то к примеру, Вы захотите сообщить всем программам рабочий каталог, временную директорию или какой-нибудь другой специфичный параметр. Тогда переменные окружения, это единственный разумный метод, ведь передавать такие параметры через командную строку глупо. Почему ?! Ну, например, приведу скрипт запуска какой-нибудь сложной системы:

Ну, как ?! Громодко ! А вот как более красиво:

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

А теперь собственно давайте познакомимся с этими переменными среды. Библиотека glibc предоставляет весь спектр функций для работы с ними в заголовочном файле stdlib.h.

Сначала познакомимся с самим массивом переменных окружения, который определен в заголовочном файле unistd.h в таком виде:

Представлет собой массив указателей на строки формата «имя=значение» и заканчивается нулевым указателем NULL. Давайте попробуем написать программу вывода всех переменных:

Данная программа выведет весь список переменных среды окружения, которые доступны программе:

Я конечно вырезал некоторые переменные, которые слишком большие, но все равно достаточно информативно и можно считать, что программа знает о среде в которой запущена практически все.

Для доступа к переменным окружения, есть несколько функций:

  • char * getenv (const char *name) — возвращает указатель на значение переменной с именем name, если переменная среды не найдена, то возвращается NULL. Не рекомендуется модифицировать значение полученной строки, так как она указывает непосредственно в массив переменных среды, и можно испортить их значения. В связи с этим также не требуется выделение дополнительной памяти для сохранения результата.
  • int setenv (const char *name, const char *value, int replace) — добавляет новое или заменяет старое значение в массиве переменных среды с именем name и значением value (даже если value пустая строка). Под новую переменную выделяется память и заносится строка вида «имя=значение«. Если в переменных среды уже есть переменная с именем name, то процесс замены контролируется параметром replace, если он равен нулю, то никаких действий не производится.
  • int putenv (char *string) — добавляет или удаляет переменную окружения. Для добавления или изменения переменной используйте строку формата «имя=значение«, для удаления просто «имя«. В отличие от setenv() функция putenv() не выделяет память для параметра, а использует указатель на значение string, поэтому после вызова этой функции любое изменение строки string автоматически приведет к изменению переменной среды. Также перед удалением строки из памяти, следует сначала удалить эту переменную из массива переменных окружения.
  • int unsetenv (const char *name) — удаляет полностью из массива переменных окружения переменную с именем name.
  • int clearenv(void) — полностью очищает массив переменных окружения.
Читайте также:  Как поменять приоритет мониторов windows

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

При вызове данной программы вы узнаете свой домашний каталог и имя пользователя. Например:

Использование переменных окружения полезно не только, когда Вам требуется настроить в нескольких программах какие-то параметры, но и для обмена данными между процессами. То есть в одной программе Вы создаете переменную, а в другой получаете значение этой переменной. Таким образом можно наладить обмен простыми короткими данными между процессами. Но, конечно, все-таки не стоит сильно злоупотреблять этой возможностью 🙂

Источник

Setting environment variables in Linux using Bash

In tcsh , I have the following script working:

What is the equivalent to the tcsh setenv function in Bash?

Is there a direct analog? The environment variables are for locating the executable.

5 Answers 5

export VAR=value will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR=’my val’ . If you want the variable to be interpolated, use double quotes, like export VAR=»$MY_OTHER_VAR» .

The reason people often suggest writing

instead of the shorter

is that the longer form works in more different shells than the short form. If you know you’re dealing with bash , either works fine, of course.

Set a local and environment variable using Bash on Linux

Check for a local or environment variables for a variable called LOL in Bash:

Sanity check, no local or environment variable called LOL.

Set a local variable called LOL in local, but not environment. So set it:

Variable ‘LOL’ exists in local variables, but not environment variables. LOL will disappear if you restart the terminal, logout/login or run exec bash .

Set a local variable, and then clear out all local variables in Bash

You could also just unset the one variable:

Local variable LOL is gone.

Promote a local variable to an environment variable:

Note that exporting makes it show up as both a local variable and an environment variable.

Exported variable DOGE above survives a Bash reset:

Unset all environment variables:

You have to pull out a can of Chuck Norris to reset all environment variables without a logout/login:

You created an environment variable, and then reset the terminal to get rid of them.

Or you could set and unset an environment variable manually like this:

Источник

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