Linux bash set command

Фундаментальные основы Linux. Часть III. Раскрытие команд командной оболочкой

Глава 12. Переменные командной оболочки

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

Символ доллара ($)

Еще одним важным интерпретируемым командной оболочкой символом является символ доллара $ . Командная оболочка будет искать переменную окружения с именем, соответствующим размещенной после символа доллара строке, и заменять данный символ и имя переменной на значение этой переменной (или ни на что в том случае, если переменной не существует).

Зависимость от регистра

Создание переменных

Кавычки

Команда set

Вы можете использовать команду set для вывода списка переменных окружения. В системах Ubuntu и Debian команда set также выведет список функций командной оболочки после списка переменных командной оболочки. Поэтому для ознакомления со всеми элементами списка переменных окружения при работе с данными системами рекомендуется использовать команду set | more .

Команда unset

Переменная окружения $PS1

Переменная окружения $PS1 устанавливает формат приветствия вашей командной оболочки. При вводе строки форматирования вы можете использовать обратный слэш для экранирования таких специальных символов, как символ \u , предназначенный для вывода имени пользователя, или \w , предназначенный для вывода имени рабочей директории. На странице руководства командной оболочки bash представлен полный список специальных символов.

Переменная окружения $PATH

Команда env

Команда env в случае использования без параметров выведет список экспортированных переменных окружения . Отличие данной команды от команды set с параметрами заключается в том, что команда set выводит список всех переменных окружения, включая те переменные, которые не экспортируются в дочерние командные оболочки.

Кроме того, команда env может также использоваться для запуска «чистой» командной оболочки (командной оболочки без наследования какого-либо окружения). Команда env -i позволяет очистить окружение дочерней командной оболочки.

Команда export

Разграничения переменных

Несвязанные переменные

В командной оболочке bash команда set -u идентична команде set -o nounset и, по аналогии, команда set +u идентична команде set +o nounset .

Практическое задание: переменные командной оболочки

1. Используйте команду echo для вывода строки «Привет», после которой должно следовать ваше имя. (Используйте переменную командной оболочки bash!)

2. Создайте переменную answer , значение которой равно 42.

3. Скопируйте значение переменной $LANG в значение переменной $MyLANG.

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

5. Выведите список всех экспортируемых переменных командной оболочки.

6. Присутствует ли информация о вашей переменной в выводе команд env и set ?

7. Уничтожьте вашу переменную answer .

8. Создайте две переменные и экспортируйте одну из них.

9. Выведите значение экспортированной переменной в дочерней интерактивной командной оболочке.

10. Создайте переменную и присвойте ей значение ‘Dumb’, после чего аналогичным образом создайте другую переменную с значением ‘do’. Используйте команду echo и две созданные переменные для вывода слова ‘Dumbledore’.

11. Найдите список экранированных с помощью обратного слэша управляющих символов на странице руководства командной оболочки bash. Добавьте управляющий символ в значение переменной PS1 для вывода времени в приветствии командной оболочки.

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

1. Используйте команду echo для вывода строки «Привет», после которой должно следовать ваше имя. (Используйте переменную командной оболочки bash!)

2. Создайте переменную answer , значение которой равно 42.

3. Скопируйте значение переменной $LANG в значение переменной $MyLANG.

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

5. Выведите список всех экспортируемых переменных командной оболочки.

6. Присутствует ли информация о вашей переменной в выводе команд env и set ?

Читайте также:  Не отправлять сообщения ошибка windows

7. Уничтожьте вашу переменную answer .

8. Создайте две переменные и экспортируйте одну из них.

9. Выведите значение экспортированной переменной в дочерней интерактивной командной оболочке.

10. Создайте переменную и присвойте ей значение ‘Dumb’, после чего аналогичным образом создайте другую переменную с значением ‘do’. Используйте команду echo и две созданные переменные для вывода слова ‘Dumbledore’.

11. Найдите список экранированных с помощью обратного слэша управляющих символов на странице руководства командной оболочки bash. Добавьте управляющий символ в значение переменной PS1 для вывода времени в приветствии командной оболочки.

Источник

Linux bash set command

This builtin is so complicated that it deserves its own section. set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables.

If no options or arguments are supplied, set displays the names and values of all shell variables and functions, sorted according to the current locale, in a format that may be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In POSIX mode, only shell variables are listed.

When options are supplied, they set or unset shell attributes. Options, if specified, have the following meanings:

Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands.

Cause the status of terminated background jobs to be reported immediately, rather than before printing the next primary prompt.

Exit immediately if a pipeline (see Pipelines), which may consist of a single simple command (see Simple Commands), a list (see Lists), or a compound command (see Compound Commands) returns a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or || , any command in a pipeline but the last, or if the command’s return status is being inverted with ! . If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit. A trap on ERR , if set, is executed before the shell exits.

This option applies to the shell environment and each subshell environment separately (see Command Execution Environment), and may cause subshells to exit before executing all the commands in the subshell.

If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed within the compound command or function body will be affected by the -e setting, even if -e is set and a command returns a failure status. If a compound command or shell function sets -e while executing in a context where -e is ignored, that setting will not have any effect until the compound command or the command containing the function call completes.

Disable filename expansion (globbing).

Locate and remember (hash) commands as they are looked up for execution. This option is enabled by default.

All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name.

Job control is enabled (see Job Control). All processes run in a separate process group. When a background job completes, the shell prints a line containing its exit status.

Read commands but do not execute them. This may be used to check a script for syntax errors. This option is ignored by interactive shells.

Set the option corresponding to option-name :

Use an emacs -style line editing interface (see Command Line Editing). This also affects the editing interface used for read -e .

Enable command history, as described in Bash History Facilities. This option is on by default in interactive shells.

Читайте также:  Windows что такое шлюз

An interactive shell will not exit upon reading EOF.

If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.

Change the behavior of Bash where the default operation differs from the POSIX standard to match the standard (see Bash POSIX Mode). This is intended to make Bash behave as a strict superset of that standard.

Use a vi -style line editing interface. This also affects the editing interface used for read -e .

Turn on privileged mode. In this mode, the $BASH_ENV and $ENV files are not processed, shell functions are not inherited from the environment, and the SHELLOPTS , BASHOPTS , CDPATH and GLOBIGNORE variables, if they appear in the environment, are ignored. If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, these actions are taken and the effective user id is set to the real user id. If the -p option is supplied at startup, the effective user id is not reset. Turning this option off causes the effective user and group ids to be set to the real user and group ids.

Exit after reading and executing one command.

Treat unset variables and parameters other than the special parameters ‘ @ ’ or ‘ * ’ as an error when performing parameter expansion. An error message will be written to the standard error, and a non-interactive shell will exit.

Print shell input lines as they are read.

Print a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

The shell will perform brace expansion (see Brace Expansion). This option is on by default.

Prevent output redirection using ‘ > ’, ‘ >& ’, and ‘ <> ’ from overwriting existing files.

If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The ERR trap is normally not inherited in such cases.

Enable ‘ ! ’ style history substitution (see History Interaction). This option is on by default for interactive shells.

If set, do not resolve symbolic links when performing commands such as cd which change the current directory. The physical directory is used instead. By default, Bash follows the logical chain of directories when performing commands which change the current directory.

For example, if /usr/sys is a symbolic link to /usr/local/sys then:

If set -P is on, then:

If set, any trap on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands executed in a subshell environment. The DEBUG and RETURN traps are normally not inherited in such cases.

If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters are set to the arguments , even if some of them begin with a ‘ — ’.

Signal the end of options, cause all remaining arguments to be assigned to the positional parameters. The -x and -v options are turned off. If there are no arguments, the positional parameters remain unchanged.

Using ‘ + ’ rather than ‘ — ’ causes these options to be turned off. The options can also be used upon invocation of the shell. The current set of options may be found in $- .

The remaining N arguments are positional parameters and are assigned, in order, to $1 , $2 , … $N . The special parameter # is set to N.

Читайте также:  Как подключить socks5 windows 10

The return status is always zero unless an invalid option is supplied.

Источник

Linux ‘set’ Command for Bash Environment Variables

Prompt Bash to behave in certain ways by setting local variables with ‘set’

The set command in Linux activates or clears specific flags or settings within the Bash shell environment.

Other shells use different methods of setting local variables.

Using the Set Command

The set command lets you control certain flags and features in Bash to determine the behavior of your scripts. These controls help to ensure that your scripts follows the intended path and certain quirks in Bash don’t turn into problems.

Start with something simple. Say you want to disable Bash’s default behavior of overwriting files the ‘-C’ flag will prevent it.

For example, executing:

Then, you can try running something like:

Normally, you’d see a pile of files and folders dumped out on your screen, but now, you’ll only receive a message letting you know that there’s no such directory.

When you’re debugging a script, you probably don’t want a partially functional script to keep on running, causing havoc or producing incorrect results. You can enable the ‘-e’ flag to stop a script immediately when something goes wrong.

On a similar note, the set command also enables you to see which command in your script is being executed followed by the result. This lets you more accurately debug by giving you a real time readout of where your script is and what the result of each command is. This super useful functionality comes from the ‘-x’ flag.

You can try it out with a simple while loop to see each iteration.

Notice how it plays out. You’ll get a direct print out of each line. Then, Bash will run the line, and give you a print out of the result, if any, and move on to the next line. This method can be a massive time saver when debugging your scripts.

In case you’ve been following along, you’ve probably noticed that the changes brought about with the set command seem permanent. They’re not. Use the plus sign(+) before any of the flags to disable them.

For more information on how the set command works and whet it can do, you can always run:

For more extensive advice about configuring built-in variables for Bash, review the Bash manual’s instructions about set.

Источник

set – Команда Linux – Команда Unix

set – чтение и запись переменных

конспект

набор имяПерем значение ?

Описание

Возвращает значение переменной varName . Если указано значение , установите для varName значение значение , создав новую переменную, если она еще не существует, и верните ее значение. Если varName содержит открытые скобки и заканчивается закрывающей скобкой, то это относится к элементу массива: символы перед первой открытой скобкой – это имя массива, а символы в скобках – это Индекс в массиве. В противном случае varName ссылается на скалярную переменную. Обычно varName является неквалифицированным (не включает в себя имена каких-либо содержащих пространства имен), и переменная этого имени в текущем пространстве имен читается или записывается. Если varName включает квалификаторы пространства имен (в имени массива, если оно ссылается на элемент массива), переменная в указанном пространстве имен читается или записывается.

Если ни одна процедура не активна, то varName ссылается на переменную пространства имен (глобальная переменная, если текущее пространство имен является глобальным пространством имен). Если процедура активна, то varName ссылается на параметр или локальную переменную процедуры, если только не была вызвана команда global , чтобы объявить varName как глобальный или если не была вызвана команда variable , чтобы объявить varName переменной пространства имен.

Опции

Смотрите также

выражение (п), Proc (п), след (п), не установлено (п)

Ключевые слова

читать, писать, переменная

Используйте команду man (% man ), чтобы увидеть, как команда используется на вашем конкретном компьютере.

Источник

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