Для того, что бы объявить переменную в bash, сперва необходимо выбрать имя этой переменной. Имя переменной регистрозависемо. Лучше всего в имени переменной использовать верхний регистр букв. Конечно же вы свободны использовать любые буквы или цифры, главное, что бы имя не начиналось с цифры. Необходимо всегда помнить о различиях между именем переменной и ее значением. Если variable1 — это имя переменной, то $variable1 — это ссылка на ее значение. «Чистые» имена переменных, без префикса $, могут использоваться только при объявлении переменный, при присваивании переменной некоторого значения, при удалении (сбросе), при экспорте и в особых случаях — когда переменная представляет собой название сигнала. Давайте переделаем наш скрипт «Hellow World» так что бы в нем появилась переменная:
#!/bin/bash STRING="Hellow World" echo $STRING
Одинарные и двойные кавычки.
Очень тяжело всегда на словах объяснить разницу между работой одинарных и двойных кавычек , проще всего показать на примере :
#!/bin/bash STRING="Hellow World 1 2" echo $STRING echo "$STRING" echo '$STRING'
результат выполнения:
Hellow World 1 2 Hellow World 1 2 $STRING
То есть, как вы видите, если заключить переменную в двойные кавычки, то форматирование не измениться. Одинарные же кавычки не производят подстановка значений переменных, то есть «$» интерпретируется как простой символ.
Так же вы можете присвоить переменной значение вывода какой либо команды, например :
#!/bin/bash STRING=`ps ax` echo $STRING
В переменную STRING записывается результат работы команды ps ax. Так же вместо обратных кавычек вы можете использовать скобки:
#!/bin/bash STRING=$(ps ax) echo $STRING
Типы переменных в bash
В отличие от большинства других языков программирования, Bash не производит разделения переменных по «типам». По сути, переменные Bash являются строковыми переменными, но, в зависимости от контекста, Bash допускает целочисленную арифметику с переменными.
Глобальные и Локальные переменные
Переменные которые ограничены скриптом или функцией называются локальными. Сценарий может экспортировать локальные переменные только дочернему процессу, т.е. командам и процессам запускаемым из данного сценария, для этого используется команда export. Небольшой пример у нас есть два скрипта 1.sh и 2.sh. В 1.sh мы объявляем переменную, после чего запускаем скрипт 2.sh и хотим использовать эту переменную во втором скрипте; 1.sh:
#!/bin/bash STRING="Hellow World" export STRING sh 2.sh
Содержание 2.sh:
#!/bin/bash echo $STRING
Результатом будет:
Глобальные переменные (или их еще называют переменные окружения) — переменные которые могут быть использованы в любом скрипте. Для того что бы просмотреть полный список этих переменных выполните env или printenv:
SHELL=/bin/bash
TERM=xterm
HISTSIZE=1000
SSH_CLIENT=172.16.1.96 61195 22
SSH_TTY=/dev/pts/0
USER=root
LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:
MC_TMPDIR=/tmp/mc-root
PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
MAIL=/var/spool/mail/root
PWD=/
INPUTRC=/etc/inputrc
LANG=en_US.UTF-8
HISTCONTROL=ignorespace
HOME=/root
SHLVL=2
MC_SID=2893
LOGNAME=root
CVS_RSH=ssh
SSH_CONNECTION=172.16.1.96 61195 172.16.1.11 22
LESSOPEN=|/usr/bin/lesspipe.sh %s
G_BROKEN_FILENAMES=1
OLDPWD=/var
_=/bin/env
Так же существует ряд зарезервированных переменных :
Variable name Definition auto_resume This variable controls how the shell interacts with the user and job control. BASH The full pathname used to execute the current instance of Bash. BASH_ENV If this variable is set when Bash is invoked to execute a shell script, its value is expanded and used as the name of a startup file to read before executing the script. BASH_VERSION The version number of the current instance of Bash. BASH_VERSINFO A read-only array variable whose members hold version information for this instance of Bash. COLUMNS Used by the select built-in to determine the terminal width when printing selection lists. Automatically set upon receipt of a SIGWINCH signal. COMP_CWORD An index into ${COMP_WORDS} of the word containing the current cursor position. COMP_LINE The current command line. COMP_POINT The index of the current cursor position relative to the beginning of the current command. COMP_WORDS An array variable consisting of the individual words in the current command line. COMPREPLY An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility. DIRSTACK An array variable containing the current contents of the directory stack. EUID The numeric effective user ID of the current user. FCEDIT The editor used as a default by the -e option to the fc built-in command. FIGNORE A colon-separated list of suffixes to ignore when performing file name completion. FUNCNAME The name of any currently-executing shell function. GLOBIGNORE A colon-separated list of patterns defining the set of file names to be ignored by file name expansion. GROUPS An array variable containing the list of groups of which the current user is a member. histchars Up to three characters which control history expansion, quick substitution, and tokenization. HISTCMD The history number, or index in the history list, of the current command. HISTCONTROL Defines whether a command is added to the history file. HISTFILE The name of the file to which the command history is saved. The default value is ~/.bash_history. HISTFILESIZE The maximum number of lines contained in the history file, defaults to 500. HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved in the history list. HISTSIZE The maximum number of commands to remember on the history list, default is 500. HOSTFILE Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. HOSTNAME The name of the current host. HOSTTYPE A string describing the machine Bash is running on. IGNOREEOF Controls the action of the shell on receipt of an EOF character as the sole input. INPUTRC The name of the Readline initialization file, overriding the default /etc/inputrc. LANG Used to determine the locale category for any category not specifically selected with a variable starting with LC_. LC_ALL This variable overrides the value of LANG and any other LC_ variable specifying a locale category. LC_COLLATE This variable determines the collation order used when sorting the results of file name expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within file name expansion and pattern matching. LC_CTYPE This variable determines the interpretation of characters and the behavior of character classes within file name expansion and pattern matching. LC_MESSAGES "This variable determines the locale used to translate double-quoted strings preceded by a ""$"" sign." LC_NUMERIC This variable determines the locale category used for number formatting. LINENO The line number in the script or shell function currently executing. LINES Used by the select built-in to determine the column length for printing selection lists. MACHTYPE A string that fully describes the system type on which Bash is executing, in the standard GNU CPU-COMPANY-SYSTEM format. MAILCHECK How often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables. OLDPWD The previous working directory as set by the cd built-in. OPTERR If set to the value 1, Bash displays error messages generated by the getopts built-in. OSTYPE A string describing the operating system Bash is running on. PIPESTATUS An array variable containing a list of exit status values from the processes in the most recently executed foreground pipeline (which may contain only a single command). POSIXLY_CORRECT If this variable is in the environment when bash starts, the shell enters POSIX mode. PPID The process ID of the shell's parent process. PROMPT_COMMAND If set, the value is interpreted as a command to execute before the printing of each primary prompt (PS1). PS3 "The value of this variable is used as the prompt for the select command. Defaults to ""'#? '""" PS4 "The value is the prompt printed before the command line is echoed when the -x option is set; defaults to ""'+ '""." PWD The current working directory as set by the cd built-in command. RANDOM Each time this parameter is referenced, a random integer between 0 and 32767 is generated. Assigning a value to this variable seeds the random number generator. REPLY The default variable for the read built-in. SECONDS This variable expands to the number of seconds since the shell was started. SHELLOPTS A colon-separated list of enabled shell options. SHLVL Incremented by one each time a new instance of Bash is started. TIMEFORMAT The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. TMOUT If set to a value greater than zero, TMOUT is treated as the default timeout for the read built-in. In an interative shell, the value is interpreted as the number of seconds to wait for input after issuing the primary prompt when the shell is interactive. Bash terminates after that number of seconds if input does not arrive. UID The numeric, real user ID of the current user.
Некоторые их этих переменных read-only, другие можно изменять, за более подробной информацией прочтите bash man.
Создание переменных типа Integer
Объявляем переменную типа Integer:
declare -i y=10 echo $y
Если вы попытаетесь присвоить буквенное значение параметру который был объявлен как Integer, то bash присвоит этом параметру значение 0: Как пример, давайте создадим скрипт script.sh:
#!/bin/bash # обьявляем x, y, z как integer declare -i x=10 declare -i y=10 declare -i z=0 z=$(( x + y )) echo "$x + $y = $z" # пробуем присвоить параметру x значение a x=a z=$(( x + y )) echo "$x + $y = $z"
На выходе мы получим:
10 + 10 = 20 0 + 10 = 10
Создание переменной типа Constant
Для создания переменной типа Constant вы можете использовать команду readonly или declare. Сперва, попробуем использовать команду readonly:
readonly var readonly varName=value
А теперь declare:
declare -r var declare -r varName=value
Давайте рассмотрим небольшой пример:
#!/bin/bash readonly DATA=/home/sales/data/feb09.dat DATA=/tmp/foo
Запустив такой скрипт мы получим:
Error ... readonly variable
Часть 1: скрипт Hellow World
Часть 2: Переменные
Часть 3: Специальные параметры
Часть 4: Одинарные и двойные кавычки. Математические операции
Часть 5: Структурные конструкции и команда test
Часть 6: Структура If…then…else
Часть 7: Подмножества и части строк. Размеры