Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How to list all variables names and their current values?

Including not only $HOME , $PWD etc but any other you have defined.

  • command-line
  • environment-variables

7ochem's user avatar

  • 5 superuser.com/questions/420295/… –  Ciro Santilli OurBigBook.com Nov 30, 2015 at 14:46
  • 9 You've accepted an incorrect answer. "printenv" only gives you the environment variables. If you truly want all variables currently declared in your shell, use "declare -p" or "typeset -p". –  Florin Andrei Jul 26, 2019 at 19:11

11 Answers 11

For bash: (the standard shell in Ubuntu)

Enter the following command in a terminal to print all the environment variables:

For further information about this command, read the printenv man page .

To show a list including the "shell variables" you can enter the next command:

This will show you not only the shell variables, but the environment variables too.

For more information related with this topic read:

  • How to list variables declared in script in bash? from SO and
  • How to print all environment variables defined (but not necessarily exported) in bash from UnixSE
  • Environment variable vs Shell variable, what's the difference?

For zsh: (an advanced shell)

Use the following command:

For more information about ZSH options, see zshoptions man page .

Fabby's user avatar

  • 21 If I go to the terminal and write MYNEWVARIABLE=Ubuntu and execute printenv it doesn't show there. Why is that, and how do those others show up? –  Strapakowsky Mar 30, 2013 at 3:30
  • 8 Probably you are seeing the difference between a shell variable and an environment variable. Try export MYNEWVARIABLE=Ubuntu and it will work as you expect. –  Rmano Oct 12, 2013 at 0:41
  • 5 if you simply execute set , it lists the variable created by you as well. Or do set | grep myvar –  Sergiy Kolodyazhnyy Jan 4, 2015 at 15:01
  • 8 printenv is an external command, so it only knows about (and prints) exported environment variables. set is an internal bash command, so it shows all the "shell variables" (unexported environment variables) as well as the exported environment variables. –  Dan Pritts Jul 30, 2015 at 15:33
  • 2 To expand on @Rmano's reply to @Strapakowsky... This will not work unset MYNEWVARIABLE; MYNEWVARIABLE=Ubuntu; printenv | grep MYNEW , but this will unset MYNEWVARIABLE; export MYNEWVARIABLE=Ubuntu; printenv | grep MYNEW , and this will unset MYNEWVARIABLE; MYNEWVARIABLE=Ubuntu printenv | grep MYNEW . Using export says "the variable I'm setting should be part of the environment that gets passed to processes, not just a variable in this shell." My third example says "the variable should be part of the environment that gets passed to THIS process, but not stick around afterward." –  Bruno Bronosky Aug 26, 2016 at 17:39

You can see all variables with the declare builtin.

If you're only interested in environment variables, use

Run help declare to see what the other options are.

geirha's user avatar

  • 5 this is far neat-er solution than POSIXLY_CORRECT=1 set and it is also worthy of mention that declare is alias (in that context) for typeset , another bash builtin. –  user359096 Feb 7, 2018 at 16:50
  • 5 This is the correct answer. –  Florin Andrei Jul 26, 2019 at 19:11
  • 3 I think this is what most people are looking for. –  WinEunuuchs2Unix Oct 18, 2019 at 23:56
  • 4 @maoizm If you want only the variable names and nothing else, it's easier to use compgen for that. compgen -e . –  geirha Feb 3, 2020 at 20:33
  • 1 @ColinFraizer try compgen -v instead –  geirha May 20, 2020 at 6:32

I know that this question is quite old and answered, but I think I can add a bit of useful information.

In all the methods described above, the procedure that is suggested is:

  • launch a terminal
  • show the environment variables using env , or printenv or whatever

The problem of these solutions are that you are seeing the environment variables of the shell that is running into the terminal . You are not seeing the environment variables available to an application run, for example, directly by the graphic interface.

This is noticeable if, for example, you use your ~/.profile , or .bashrc , or .zshenv (depending on your shell) to modify the environment variables --- like the classic addition of directories to the path.

To see the environment variables available to the application started directly in the graphic environment, you can do the following (in Gnome Shell, I am sure there is an equivalent method in all the other DE):

  • press Alt-F2
  • run the command xterm -e bash --noprofile --norc

(Or, if you do not have xterm , gnome-terminal -- bash --noprofile --norc --- thanks to @Mike Nakis for the comment).

You now have a terminal with a shell that did not add any environment variables. You can use env here to list all your environment variables:

Example of the bare shell

Obviously the new shell will have the environment variables added by the system files, but that variables should be available (by inheritance) to all programs in the system anyway.

I am posting this because it's the fourth time I have to search this trick again, checking my .pam_environment file. So now I will find it faster (and in the process, I hope helping someone else...)

Rmano's user avatar

  • Requires you have a desktop environment, not useful for server CLI-only folk. –  K7AAY Oct 21, 2013 at 18:21
  • 7 Yes --- but then for CLI only the previous answer is ok. I was just pointing out that sometime you need to check environment variables available to application started by the graphical environment, which is not the same set you see when you start a terminal in it. For example, if you are trying to understand why your Kile app can't compile a LaTeX file, while in a terminal you can, the trick I posted here will help a lot. –  Rmano Oct 21, 2013 at 20:36
  • 4 Thanks for a very useful answer! I just linked to it from help.ubuntu.com/community/… –  Gunnar Hjalmarsson Jan 2, 2014 at 17:06
  • Thanks. Did you recommend xterm -e bash --noprofile --norc because the startup files are not read and executed when Ubuntu is started with graphical interface ? See askubuntu.com/q/1025845/1471 –  Tim Apr 17, 2018 at 14:49
  • 2 the right command to execute nowadays (Ubuntu 18.04) is gnome-terminal -- bash --noprofile --norc –  Mike Nakis Apr 28, 2019 at 11:10

To list the environment variables in terminal with CTRL + ALT + T you can use env command.

for example :

hope that helps.

Raja G's user avatar

  • I've noticed that env misses some variables o_O. specifically after sourcing a VAR=VAL file. –  ThorSummoner Aug 2, 2017 at 19:43
  • 3 @ThorSummoner The answer here might help stackoverflow.com/questions/15474650/… –  georaldc Aug 14, 2017 at 17:48

In bash using compgen:

Seth's user avatar

  • 3 This should be the accepted answer, as all others list more than just the name itself. In my case some variables contain multiline values which makes the other solutions not feasable. –  Mene Nov 9, 2017 at 15:20
  • 3 A variant: compgen -v | while read line; do declare -p $line; done –  Eljay Dec 13, 2018 at 17:58
  • @Eljay what is the difference to just declare -p ? –  DJCrashdummy Jun 15, 2023 at 8:13
  • @DJCrashdummy • declare -p won't include things like BASH_COMMAND , BASH_SUBSHELL , COMP_WORDBREAKS , HISTCMD , LINENO , RANDOM , SECONDS . –  Eljay Jun 15, 2023 at 11:05
  • @Eljay well... at least for me declare -p "includes" resp. lists them all (and FUNCNAME additionally), but you are kind of right: the values are not shown and also values of arrays are not shown . do you know why this is? -- so IMHO your line is the most comprehensive way to do this, even with all values of arrays including indexes! –  DJCrashdummy Jun 22, 2023 at 10:53

Most solutions here either print only environment variables, or have the drawback that env or (set -o posix; set) do not print values in easily parseable form (try to print variable A=$'a\r\nb', it has multiple lines...).

Here is a function that will print all variables, one variable per line, in the POSIX escaped form (works properly for simple text variables, does not work for arrays):

Thanks to @tmgoblin for pointing out the use of compgen -v.

Ján Lalinský's user avatar

If you want a specific environment variable, rather than printing them all with printenv , you can for example print it by doing echo "$PWD"

inigo333's user avatar

  • The quotes are unnecessary; i.e.: echo $PATH or echo $USER . This will print the environment variable's value. The dollar sign operator is the only thing needed to access the value of a variable or command. –  NOCARRIER Jun 8, 2023 at 19:42

env is a POSIX 7 way :

Sample output:

It only shows exported variables: non-exported variables are not usually considered "environment variables".

Prefer that over printenv , which is not POSIX. Both seem to do the same thing without arguments: https://unix.stackexchange.com/questions/123473/what-is-the-difference-between-env-and-printenv

Community's user avatar

  • Already mentioned two years ago: askubuntu.com/a/276162/158442 –  muru Nov 30, 2015 at 15:00
  • @muru fair enough. Wish it had made env more visible with better formatting, and I've added more info. –  Ciro Santilli OurBigBook.com Nov 30, 2015 at 15:01
  • That's what editing is for. –  muru Nov 30, 2015 at 15:02
  • printenv will show all the global environoment variables
  • env, global environment variable after login modification
  • set, will display all local environment variable, relative to the session (usually the local var is the global + the particular of the session)

kelvinelove's user avatar

printenv only lists exported variables, command + alt + $ ( "\e$": complete-variable ) will list all variables.

user1133275's user avatar

Script to dump everything, sort, and highlight all $ENVS and $variables declared in the session.

Luke Mlsna's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged command-line bash environment-variables ..

  • The Overflow Blog
  • Who owns this tool? You need a software component catalog
  • Featured on Meta
  • Upcoming privacy updates: removal of the Activity data section and Google...
  • Changing how community leadership works on Stack Exchange: a proposal and...
  • Notifying users about the policy on AU concerning AI-generated content
  • AI-generated content is not permitted on Ask Ubuntu

Hot Network Questions

  • Can Survival Models model the time at which a random variable will first pass a certain point?
  • Examples of stochastic processes that don't exist
  • Optimal Solution for OddsBeforeEvens Wolfram Challenge
  • How can I make this code cleaner and stop having to keep checking the same values for each switch
  • Snap cubes to each other
  • Why did it take so long for the U.S. government to give Medicare the power to negotiate prescription drug prices directly with drug companies?
  • Can I run wires from separate panels through the same conduit?
  • What happens when the Sitecore license got expired?
  • Are you guilty of tampering with evidence if you hide a morally dubious act for which you didn't know for certain was a crime?
  • Old romantic horror movie about a guy that fell in love with a girl and later found out she's a ghost
  • will one piece of sod immediately die?
  • Do American supermarkets have shopping cart conveyors or shopping cart coins?
  • Is it legal for a bank to trap you in an ATM vestibule?
  • Is it fine to email several people regarding internship programs and potentially have to turn down one?
  • How does EXT4 handle sudden lack of space in the underlying storage?
  • How to efficiently transport troops from orbit
  • How to find a "short" walk that visits all vertices of a strongly connected directed graph
  • Make a single object transparent in viewport shading
  • Manager asked for home address without giving a reason. Should I have provided it?
  • Toddler keeps lifting mattress up and putting his legs into the mattress rack - how to prevent?
  • Is it okay for a co-author to share an unfinished manuscript with others?
  • Weak Power Hypothesis and Dependent Choice
  • Has the Niger junta explained why they expelled French but not US troops?
  • Derivation of Coulomb's law from Maxwell's equations

bash variables list

Previous: Bourne Shell Variables , Up: Shell Variables   [ Contents ][ Index ]

5.2 Bash Variables

These variables are set or used by Bash, but other shells do not normally treat them specially.

A few variables used by Bash are described in different chapters: variables for controlling the job control facilities (see Job Control Variables ).

($_, an underscore.) At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

The full pathname used to execute the current instance of Bash.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -s option to the shopt builtin command (see The Shopt Builtin ). The options appearing in BASHOPTS are those reported as ‘ on ’ by ‘ shopt ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized. Assignments to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. (see Bourne Shell Builtins ). Elements added to this array appear in the alias list; however, unsetting array elements currently does not cause aliases to be removed from the alias list. If BASH_ALIASES is unset, it loses its special properties, even if it is subsequently reset.

An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source ) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC . The shell sets BASH_ARGC only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV . The shell sets BASH_ARGV only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

When referenced, this variable expands to the name of the shell or shell script (identical to $0 ; See Special Parameters , for the description of special parameter 0). Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0 . If BASH_ARGV0 is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin (see Bourne Shell Builtins ). Elements added to this array appear in the hash table; however, unsetting array elements currently does not cause command names to be removed from the hash table. If BASH_CMDS is unset, it loses its special properties, even if it is subsequently reset.

The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If BASH_COMMAND is unset, it loses its special properties, even if it is subsequently reset.

The value is used to set the shell’s compatibility level. See Shell Compatibility Mode , for a description of the various compatibility levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., 42) corresponding to the desired compatibility level. If BASH_COMPAT is unset or set to the empty string, the compatibility level is set to the default for the current version. If BASH_COMPAT is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid values correspond to the compatibility levels described below (see Shell Compatibility Mode ). For example, 4.2 and 42 are valid values that correspond to the compat42 shopt option and set the compatibility level to 42. The current version is also a valid value.

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. See Bash Startup Files .

The command argument to the -c invocation option.

An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file ( ${BASH_SOURCE[$i+1]} ) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number.

A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command.

An array variable whose members are assigned by the ‘ =~ ’ binary operator to the [[ conditional command (see Conditional Constructs ). The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the n th parenthesized subexpression.

An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}

Incremented by one within each subshell or subshell environment when the shell begins executing in that environment. The initial value is 0. If BASH_SUBSHELL is unset, it loses its special properties, even if it is subsequently reset.

A readonly array variable (see Arrays ) whose members hold version information for this instance of Bash. The values assigned to the array members are as follows:

The major version number (the release ).

The minor version number (the version ).

The patch level.

The build version.

The release status (e.g., beta1 ).

The value of MACHTYPE .

The version number of the current instance of Bash.

If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when ‘ set -x ’ is enabled to that file descriptor. This allows tracing output to be separated from diagnostic and error messages. The file descriptor is closed when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting BASH_XTRACEFD to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed.

Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX -mandated minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent.

Used by the select command to determine the terminal width when printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE} . This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: TAB , for normal completion, ‘ ? ’, for listing completions after successive tabs, ‘ ! ’, for listing alternatives on partial word completion, ‘ @ ’, to list completions if the word is not unmodified, or ‘ % ’, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The key (or final key of a key sequence) used to invoke the current completion function.

The set of characters that the Readline library treats as word separators when performing word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is subsequently reset.

An array variable consisting of the individual words in the current command line. The line is split into words as Readline would split it, using COMP_WORDBREAKS as described above. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion ). Each array element contains one possible completion.

An array variable created to hold the file descriptors for output from and input to an unnamed coprocess (see Coprocesses ).

An array variable containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset.

If Bash finds this variable in the environment when the shell starts with value ‘ t ’, it assumes that the shell is running in an Emacs shell buffer and disables line editing.

Expanded and executed similarly to BASH_ENV (see Bash Startup Files ) when an interactive shell is invoked in POSIX Mode (see Bash POSIX Mode ).

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch as a floating point value with micro-second granularity (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses its special properties, even if it is subsequently reset.

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it loses its special properties, even if it is subsequently reset.

The numeric effective user id of the current user. This variable is readonly.

A colon-separated list of shell patterns (see Pattern Matching ) defining the list of filenames to be ignored by command search using PATH . Files whose full pathnames match one of these patterns are not considered executable files for the purposes of completion and command execution via PATH lookup. This does not affect the behavior of the [ , test , and [[ commands. Full pathnames in the command hash table are not subject to EXECIGNORE . Use this variable to ignore shared library files that have the executable bit set, but are not executable files. The pattern matching honors the setting of the extglob shell option.

The editor used as a default by the -e option to the fc builtin command.

A colon-separated list of suffixes to ignore when performing filename completion. A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is ‘ .o:~ ’

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main" . This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.

This variable can be used with BASH_LINENO and BASH_SOURCE . Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]} . The caller builtin displays the current call stack using this information.

If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort.

A colon-separated list of patterns defining the set of file names to be ignored by filename expansion. If a file name matched by a filename expansion pattern also matches one of the patterns in GLOBIGNORE , it is removed from the list of matches. The pattern matching honors the setting of the extglob shell option.

An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect. If GROUPS is unset, it loses its special properties, even if it is subsequently reset.

Up to three characters which control history expansion, quick substitution, and tokenization (see History Expansion ). The first character is the history expansion character, that is, the character which signifies the start of a history expansion, normally ‘ ! ’. The second character is the character which signifies ‘quick substitution’ when seen as the first character on a line, normally ‘ ^ ’. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, usually ‘ # ’. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.

The history number, or index in the history list, of the current command. Assignments to HISTCMD are ignored. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset.

A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ‘ ignorespace ’, lines which begin with a space character are not saved in the history list. A value of ‘ ignoredups ’ causes lines which match the previous history entry to not be saved. A value of ‘ ignoreboth ’ is shorthand for ‘ ignorespace ’ and ‘ ignoredups ’. A value of ‘ erasedups ’ causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE . The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL .

The name of the file to which the command history is saved. The default value is ~/.bash_history .

The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files.

A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit ‘ * ’ is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, ‘ & ’ matches the previous history line. ‘ & ’ may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE . The pattern matching honors the setting of the extglob shell option.

HISTIGNORE subsumes the function of HISTCONTROL . A pattern of ‘ & ’ is identical to ignoredups , and a pattern of ‘ [ ]* ’ is identical to ignorespace . Combining these two patterns, separating them with a colon, provides the functionality of ignoreboth .

The maximum number of commands to remember on the history list. If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files.

If this variable is set and not null, its value is used as a format string for strftime to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines.

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. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, Bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, or does not name a readable file, Bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared.

The name of the current host.

A string describing the machine Bash is running on.

Controls the action of the shell on receipt of an EOF character as the sole input. If set, the value denotes the number of consecutive EOF characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value, or has no value, then the default is 10. If the variable does not exist, then EOF signifies the end of input to the shell. This is only in effect for interactive shells.

The name of the Readline initialization file, overriding the default of ~/.inputrc .

If Bash finds this variable in the environment when the shell starts, it assumes that the shell is running in an Emacs shell buffer and may disable line editing depending on the value of TERM .

Used to determine the locale category for any category not specifically selected with a variable starting with LC_ .

This variable overrides the value of LANG and any other LC_ variable specifying a locale category.

This variable determines the collation order used when sorting the results of filename expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the locale used to translate double-quoted strings preceded by a ‘ $ ’ (see Locale-Specific Translation ).

This variable determines the locale category used for number formatting.

This variable determines the locale category used for data and time formatting.

The line number in the script or shell function currently executing. If LINENO is unset, it loses its special properties, even if it is subsequently reset.

Used by the select command to determine the column length for printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format.

How often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking.

An array variable created to hold the text read by the mapfile builtin when no variable name is supplied.

The previous working directory as set by the cd builtin.

If set to the value 1, Bash displays error messages generated by the getopts builtin command.

A string describing the operating system Bash is running on.

An array variable (see Arrays ) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

If this variable is in the environment when Bash starts, the shell enters POSIX mode (see Bash POSIX Mode ) before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, Bash enables POSIX mode, as if the command

had been executed. When the shell enters POSIX mode, it sets this variable if it was not already set.

The process ID of the shell’s parent process. This variable is readonly.

If this variable is set, and is an array, the value of each set element is interpreted as a command to execute before printing the primary prompt ( $PS1 ). If this is set but not an array variable, its value is used as a command to execute instead.

If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see Controlling the Prompt ). Characters removed are replaced with an ellipsis.

The value of this parameter is expanded like PS1 and displayed by interactive shells after reading a command and before the command is executed.

The value of this variable is used as the prompt for the select command. If this variable is not set, the select command prompts with ‘ #? ’

The value of this parameter is expanded like PS1 and the expanded value is the prompt printed before the command line is echoed when the -x option is set (see The Set Builtin ). The first character of the expanded value is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is ‘ + ’.

The current working directory as set by the cd builtin.

Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to this variable seeds the random number generator. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

Any numeric argument given to a Readline command that was defined using ‘ bind -x ’ (see Bash Builtin Commands when it was invoked.

The contents of the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The position of the mark (saved insertion point) in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ). The characters between the insertion point and the mark are often called the region .

The position of the insertion point in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The default variable for the read builtin.

This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment. The number of seconds at shell invocation and the current time are always determined by querying the system clock. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

This environment variable expands to the full pathname to the shell. If it is not set when the shell starts, Bash assigns to it the full pathname of the current user’s login shell.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -o option to the set builtin command (see The Set Builtin ). The options appearing in SHELLOPTS are those reported as ‘ on ’ by ‘ set -o ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested.

This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support /dev/urandom or arc4random , so each returned number has no relationship to the numbers preceding it. The random number generator cannot be seeded, so assignments to this variable have no effect. If SRANDOM is unset, it loses its special properties, even if it is subsequently reset.

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. The ‘ % ’ character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

A literal ‘ % ’.

The elapsed time in seconds.

The number of CPU seconds spent in user mode.

The number of CPU seconds spent in system mode.

The CPU percentage, computed as (%U + %S) / %R.

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.

The optional l specifies a longer format, including minutes, of the form MM m SS . FF s. The value of p determines whether or not the fraction is included.

If this variable is not set, Bash acts as if it had the value

If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.

If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin (see Bash Builtin Commands ). The select command (see Conditional Constructs ) terminates if input does not arrive after TMOUT seconds when input is coming from a terminal.

In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive.

If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell’s use.

The numeric real user id of the current user. This variable is readonly.

Bash Variables Explained: A Simple Guide With Examples

Master Bash variables with the help of these explanations and examples.

Variables are used for storing values of different types during program execution. There are two types of variables in Bash scripting: global and local.

Global variables can be used by all Bash scripts on your system, while local variables can only be used within the script (or shell) in which they're defined.

Global variables are generally provided on the system by default and are mainly environment and configuration variables. Local variables, on the other hand, are user-defined and have arbitrary uses.

Bash Local Variables

To create a variable, you need to assign a value to your variable name. Bash is an untyped language, so you don't have to indicate a data type when defining your variables.

Bash also allows multiple assignments on a single line:

Just like many other programming languages, Bash uses the assignment operator = to assign values to variables. It's important to note that there shouldn't be any spaces on either side of the assignment operator. Otherwise, you'll get a compilation error.

Related: What Does "Bash" Mean in Linux?

Another key point to note: Bash doesn't allow you to define a variable first and then assign a value to it later. You must assign a value to the variable at creation.

Sometimes, you may need to assign a string that has a space in it to your variable. In such a case, enclose the string in quotes.

Notice the use of single quotes. These quotes are also called "strong quotes" because they assign the value precisely as it's written without regard to any special characters.

In the example above, you could have also used double quotes ("weak quotes"), though this doesn't mean they can always be used interchangeably. This is because double quotes will substitute special characters (such as those with $ ), instead of interpreting them literally.

See the example below:

If you want to assign a command-line output to your variable, use backquotes ( `` ). They'll treat the string enclosed in them as a terminal command and return its result.

Parameter Expansion in Bash

Parameter Expansion simply refers to accessing the value of a variable. In its simplest form, it uses the special character $ followed by the variable name (with no spaces in between):

You can also use the syntax ${variableName} to access a variable's value. This form is more suitable when confusion surrounding the variable name may arise.

If you leave out the curly brackets, ${m}ical will be interpreted as a compound variable (that doesn't exist). This use of curly brackets with variables is known as "substitution".

Global Variables

As mentioned earlier, your Linux system has some built-in variables that can be accessed across all of your scripts (or shells). These variables are accessed using the same syntax as local variables.

Related: How to Create and Execute Bash Scripts in Linux

Most of these variables are in BLOCK letters. However, some are single characters that aren't even alphanumeric characters.

Here are some common useful global variables:

HOME : Provides the user's home directory

SHELL : Provides the type of shell you're using (e.g Bash, csh..etc)

? : Provides the exit status of the previous command

To get a list of global variables on your system, run the printenv (or env) command:

Loops in Bash Scripting

Now you know what variables are, how to assign them, and how to perform basic Bash logic using them.

Loops enable you to iterate through multiple statements. Bash accommodates for loops and while loops with a simple syntax for all of your looping needs.

If you're mastering the art of Bash development, for loops ought to be next up on your list.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How do I see a list of all currently defined environment variables in a Linux bash terminal?

In a Linux bash terminal, there are often many environment variables that have been set, like $PATH and $HOME .

Is it possible to see all of the environment variables that have been set? How?

  • environment-variables

bluish's user avatar

  • 6 askubuntu.com/questions/275965/… –  Ciro Santilli OurBigBook.com Nov 30, 2015 at 14:35

5 Answers 5

TL;DR: use (set -o posix ; set)

According to the Bash manual you can use the set built-in command to show all of the environment variables that have been set. The set command will also display the definitions of any functions. If you only want to see the variables, and not the functions, then you can turn on POSIX mode before running the set command. The easiest way to do that is with set -o posix , but that will leave POSIX mode on until you turn it off with set +o posix .

Therefore, the following command will show all of the defined environment variables by using a subshell without affecting POSIX compliance in your current shell.

@RedGrittyBrick and @iglvzx suggested using the env command, however this command will not provide a complete listing of environment variables. env will only show the varaibles that have been marked for export. Compare the output of env | sort and export -p and you will see what I mean. You can run comm -23 <(set -o posix; set) <(env|sort) if you want to see which environment variables are not being exported.

The reason for the discrepancy is that env is a separate executable as opposed to set which is a shell built-in command. According to the Bash manual, when a command is executed that is not a shell built-in command or function it will only receive environment variables that have been marked for export in Bash . There are many variables that are not exported. Therefore, if you wish to see all of the variables that your shell has defined, you must use the set command as stated in the manual.

You can easily test this behavior for yourself using the following commands.

You will see that set provides output while env does not.

Starfish's user avatar

  • > (set -o posix ; set) I did not know that non-exported variables go to a subshell. Aaah...: stackoverflow.com/questions/51903718/… –  geek-merlin Mar 21, 2021 at 18:25
  • I get set: no such option: posix . –  hugo der hungrige Oct 31, 2022 at 14:29
  • @hugoderhungrige what version of bash are you using? bash --version –  Starfish Nov 30, 2022 at 22:02
  • @Starfish 5.1.16(1)-release –  hugo der hungrige Dec 1, 2022 at 10:36

The env command with no arguments will print a list of the "exported" environment variables and their values. These variables are made visible to subprocesses - many other environment variables are not shown with this, and used inside the running shell only, eg for configuration.

Volker Siegel's user avatar

  • 13 I prefer printenv , since both env and set have other functions than just outputting the environment. –  iglvzx May 4, 2012 at 5:04
  • 6 env will only print a list of environment variables that have been marked for export. It will not print all variables. –  Starfish Sep 7, 2013 at 5:19
  • 5 @Starfish is right - that means this accepted answer was very wrong. Edited to say it's listing exported variables only. –  Volker Siegel Jul 1, 2014 at 0:12
  • Why isn't this the top answer. It's so much simpler and more memorable. –  stevec Jan 25, 2020 at 8:39

prints shell variables (but not the values).

prints exported variables i.e. those that get inherited by processes this shell starts (but not their values).

Difference between shell and exported variables: https://unix.stackexchange.com/questions/3507/difference-between-environment-variables-and-exported-environment-variables-in-b?rq=1

Community's user avatar

I arrived here from a search for how to order the output of env alphabetically ; it's quite simple

  • the -f option makes sort ignore case, which is what you probably want 99% of the time

stevec's user avatar

Combining some of the previous answers, I find the following useful:

  • compgen -v : Print all variables names, either local or exported.
  • sort : Alphabetical order.
  • ${!var} : Get the value of $var (variable indirection).
  • -z condition : Check if value is null, else print "variable=value".

Note: printenv is great also, but it will only show a list of environment variables that have been exported, not local/bash variables.

Noam Manos's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged environment-variables ..

  • The Overflow Blog
  • Who owns this tool? You need a software component catalog
  • Featured on Meta
  • Upcoming privacy updates: removal of the Activity data section and Google...
  • Changing how community leadership works on Stack Exchange: a proposal and...

Hot Network Questions

  • Would a giant ball on earth roll towards the poles?
  • Can I run wires from separate panels through the same conduit?
  • How is this "bread" puffing up without yeast or baking soda?
  • How to replace one item with another in itemize?
  • What happens when the Sitecore license got expired?
  • I've hit the limit of what ChatGPT can teach me about game development in GDScript — what strategies can I use to keep making progress?
  • What happens if someone requests asylum in Vatican City?
  • Has the Niger junta explained why they expelled French but not US troops?
  • How not to sound midi without real instrument?
  • Can I take a gas canister on the MS Sarfaq Ittuk ferry?
  • How does EXT4 handle sudden lack of space in the underlying storage?
  • How to not fear the supernatural?
  • Valid reason for not having plate armor in early medieval, low-magic fantasy setting?
  • Make a single object transparent in viewport shading
  • What was the ‘obvious’ new answer to Asimov’s Pâté de Foie Gras made possible by scientific advance?
  • Can I raise my ceiling in my shed?
  • PLATO BRONCE ESCUDO HISPAN TE IND REX NG 8R P
  • Space shuttle HUD - flight director vs velocity vector
  • Median of a set with even number of elements
  • Did Ronald Fisher ever say anything on varying the threshold of significance level?
  • Isn't there another word for someone who puts together scissors?
  • How is 学习紧张和劳动并不矛盾 the answer to 那位中学生家长展示的特别简历说明……?
  • Industrial Geothermal smelting power
  • Examples of stochastic processes that don't exist

bash variables list

How-To Geek

How to list environment variables on linux.

Inspect your environment.

Quick Links

What are linux environment variables, how to show an environment variable's value, how to list environment variables using printenv, some common environment variables, environmental inspections, key takeaways.

To list environment variables on Linux, use the printenv command. That will show you all environment variables, but you can get searchable results by piping it into the less command. Alternatively, use grep to check specific environment variables.

On Linux, environment variables hold important values and settings. Scripts, applications, and shells read these values, often to configure themselves, or to control their behavior. Here are several ways to show environment variables in your terminal, and how to interpret the list as well.

Variables hold values for us. When a process needs to know what the value is, it looks up the variable by name in a list, and reads the value from it. Although variable names cannot be changed, their values can be. An environment variable, like any other variable, is a combination of a name and a value. The name is unique, set when the variable is created, and it last for the lifetime of the environment variable.

Our various test computers have an average of 50 environment variables on each of them.

You won't often change system environment variables, but you can if you need to. For example, you might like to increase the size of your Bash shell command history cache. You can edit the value of the $HISTSIZE environment variable in your ".bashrc" file to set a new upper limit for the number of remembered commands.

That's neat and convenient, but it isn't something you'll be doing often. Environment variables tend to be left at their defaults or they're changed once and then forgotten about. They're not something you'll tinker with often.

Nonetheless, it is worthwhile knowing how to check the environment variables that are defined and in use on your computer. Printing the environment variables to a terminal window lets you see their values, and shows you what aspects of your Linux experience are governed by these background values.

You can use echo to see the value stored in an environment variable. To do that you'll need to know the name of the environment variable in advance.

Using echo to see the values stored in environment variables

There are two methods commonly used to show the names and values of all the environment variables on Linux. They are the env and the printenv commands.

The printenv command is the official way to do it. The command was written specifically for this purpose . The env command has an altogether different purpose .

env is used to run an application with temporary, user-specified, values for environment variables. These override the real stored values, and allow the application to run in a modified environment. If you invoke env with no command line parameters, its default action is to list the environment variables.

We may as well use the tool designed for the job, rather than depend on the side-effect of a tool that has been invoked incorrectly, so we'll be using printenv to check environment variables in our examples.

The printenv command lets you show environment variables and is very straightforward in practice. It has very few options. You can use the --version option to find out the release number of the version on your computer, and you can use the --help command to see a short description of these two and one other command line option.

The other option is the -0 (null terminator) option. Usually, printenv lists the environment variables one per line, by adding a newline character to the end of each line. The -0 option replaces that newline character with a null byte. You would use this option if you were piping the output into another application that didn't need the newline characters.

printenv -0

Using printenv with the -0 option

The effect of the -0 option in a terminal window is to cram the output together into an impenetrable wall of text.

The unreadable output from printenv when the -0 option is used

It's practically impossible to make sense of the environment variables listed in this format. It'll be a rare occurrence if you ever need to use the -0 option. Let's drop it, and try again.

Using the printenv command with no options

The output is printed with one environment variable per line. By convention, environment variable names always use uppercase characters. Immediately after the variable name is an equals sign " = ", followed by the value that the environment variable is set to.

The standard output from printenv, with one environmental variable per line.

There's still a lot of output, so you might find it easier to pipe the environment variables into less .

printenv | less

Piping printenv into the less file viewer

This lets you scroll through the list of environment variables, and to search the list as well.

The output from printenv in the less file viewer

If you know something about the environment variable you're interested in, you can use grep to find the likely candidates. Suppose you know there's an environment variable that has the word "display" in it. We can search the list like this:

printenv | grep DISPLAY

Using grep to filter the results from printenv

The default environment variables on different Linux computers are subject to the preferences of the maintainers of the various distributions, desktop environments , and shells. So when you're checking environment variables on your Linux device, you may see varying results.

Here are some of the more common environment variables you're likely to find on a Linux computer using the GNOME desktop environment .

  • BASHOPTS : The list of command line options that were used when bash was launched.
  • BASH_VERSION : The version of bash.
  • COLUMNS : The width of the terminal in columns.
  • DIRSTACK : The stack of directories for use with the pushd and popd commands .
  • HISTFILESIZE : The maximum number of lines of command history that can be written to the history file.
  • HISTSIZE : The maximum number of lines of command history allowed to be stored in memory. If you go past this number, previously remembered commands are overwritten in memory. When you close your terminal window, the command history is written to the history file.
  • HOME : The current user's home directory.
  • HOSTNAME : The name of the computer .
  • IFS : The internal field separator that is used to parse user input. The default value is a space.
  • LANG : The current language and localization settings, including character encoding.
  • LS_COLORS : This defines the codes that are used to add color to the output from ls.
  • MAIL : The path to the current user's Linux mailbox.
  • OLDPWD : The previous working directory.
  • PS1 : The primary command prompt definition. This defines what the prompt in your terminal window looks like.
  • PATH : A colon-separated list of directories that are searched, in order, for a matching command or application when you type a command into the shell.
  • PWD : The current working directory.
  • SHELL : The name of your default shell .
  • TERM : The type of terminal that is emulated when you run a shell.
  • UID : The user identifier of the current user.
  • USER : The current user.
  • _ : The most recently executed command. If you use printenv to list this, it'll always be printenv .

To list all of your environment variables, use printenv . Pipe the output through grep to filter the results, and use echo to print the value of a specific, known environment variable.

LinuxSimply

Home > Bash Scripting Tutorial > Bash Functions > Return Values From Bash Function

Return Values From Bash Function

Mitu Akter Mou

Return values are an integral part of a Bash function. The bash function returns values by using the return statement. There are some other techniques as well like using echo command or global variables. In this article, I will show 6 examples of how the bash function returns values such as integer, string, boolean, and array. Additionally, the importance of return values used in error handling will be addressed. I will also cover some pitfalls in returning values and their solutions for more robust bash scripting.

What is a Function in Bash?

Bash function is a set of commands grouped under a single name that is reusable and performs a specific task. To make a script more readable and organized, using the bash function is a good idea. It helps to avoid writing the same code or commands repeatedly. You can just call the function anywhere in the script to accomplish the desired task. The bash function uses return values to indicate the success or failure of the last executed command.

The syntax of a bash function is as follows:

function_name: This is the name you give to your function. It follows the same rules as variable names in Bash. Also, you can use the function keyword before the function name to create a function.

(): These parentheses indicate the start and end of the function parameter list. You can omit the parentheses if your function doesn’t take any parameters.

# Commands or code blocks: This is the function body where the commands or code blocks are placed to execute the function.

{}: These curly braces contain the body of the function.

What are Return Values in Bash Function?

Returns values are the values that a bash function returns through the exit status when the function is completed. The exit status captures the return value of the bash function which is stored in a special variable $? . A return statement can be used to return an integer value between 0 and 255. Here, 0 indicates success and a non-zero value indicates failure of the last executed command. To return other values like string or array, using echo command or global variables is a great way.

6 Examples of Return Values From Bash Function

In this section, how the bash function returns one value or multiple is discussed. Additionally, the bash function can return values as strings or arrays using echo command or global variables. Most importantly, these return values can be used in handling errors. Let’s delve into the details.

1. Return One Value as Integer

To return one integer value between 0 to 255 from the bash function, use the return statement. This statement ends the function by returning the exit status to the caller function. The exit status is the return value of the bash function. Follow the script to see how it works:

First, a Bash function is defined named multiply_numbers that takes two parameters (num1 and num2), calculates their product (multiplication), and returns the result as the exit status. The local keyword is used to make the variable local to the function. multiply_numbers 5 3 calls the function with arguments 5 and 3, and the exit status of the function is captured in the variable “result” using $? . echo "Multiplication result: $result" prints the multiplication result obtained from the exit status of the function.

returning values as integer in bash

As you can see, the bash function returns 15 and prints it in the terminal. However, this script cannot return a value more than 255. To avoid this issue, follow the Exceeding Return Value Limit section.

2. Return Multiple Values

Multiple values can be returned from the bash function using a Bash array . For that, define a function and then create an array that includes the values that will be returned from the function using the echo command. Here’s how:

The script defines a function multiple_values that creates an array with three values (“Ubuntu”, “Linux”, and “Red-hat”). echo "${array[@]}" prints the elements of the array separated by spaces. Then the function multiple_values is called, and its output is captured in the result array. The $(...) syntax is used to execute the function and capture its output as an array. Finally, the script prints the individual values from the result array using array indexing (${result[0]}, ${result[1]}, and ${result[2]}) .

return multiple values from bash function

This image demonstrates multiple values returned from a Bash function using an array.

3. Return Value as String

Like other programming languages, Bash does not support returning string values directly from the bash function. So to return the value as the string, use the echo command with the command substitution method. Follow the script to learn how to return string value from the function:

Here, the Bash function named “greetings” takes a parameter “name”, echoes a greeting using the provided name, and then echoes a “Good Morning” message. message=$(greetings "John") calls the “greetings” function with the argument “John”. The output of the function (both lines of greeting) is captured in the variable “message” using command substitution ($(...)) .

returning string from bash function

Upon executing the script, it displays the greeting message of the bash function.

4. Return Value as Boolean

There is no boolean type in the Bash function, but the exit status of a command can be used to represent a boolean value. Usually, a command with a successful execution returns an exit status of 0 (which is considered true ), whereas a non-zero exit status is considered false . Here’s an example of a Bash function that returns a boolean value based on the file’s existence:

This script checks if a file exists or not by creating a bash function named “file_exists”. The function takes one parameter, file_path , and checks if the file specified by file_path exists using the -f test in a conditional expression. If the file exists, the function returns 0 (true) and prints “File exists!”. If it doesn’t exist, it returns 1 (false) and echoes “File not found.”.

checking file existence using bash return value as boolean

Since “file.txt” is in the system, it shows “File exists”.

5. Return Values (Array) Using Global Variable

A global variable in bash is a variable declared outside of a function. It can be accessed and changed both inside and outside of the function. Because of this, there is a high chance of an unexpected error. Therefore, it is recommended to use local variables.

Now, see how the values are returned from the Bash function using a global variable:

declare -a numbers_array declares a global array variable named numbers_array . The -a flag indicates that it’s an indexed array . The get_numbers function is created to assign values (1, 2, 3) to the global array variable. After calling the function, it prints the elements of the global array using ${numbers_array[@]} .

return values using global variables

As you can see, the values of the global array are shown in the terminal.

6. Return Values in Error Handling

Return values can be used to gracefully handle errors in the Bash function. In this example, the exit status is checked before performing the division operation using the $? variable. If the denominator is 0, the script will show an error message. Here’s the complete bash script for this:

The division function takes two parameters numerator and denominator. Before performing the division, it checks if the denominator is 0 or not. If the divisor is 0, the function prints an error message and returns a non-zero value to indicate failure. When the division is successful, the function prints the result and returns 0 to indicate success.

local result=$((numerator / denominator)) performs the division of the numerator by the denominator and stores the result in the result variable. division 10 0 calls the division function with arguments 10 and 0. The condition $? -eq 0 within the if statement checks the exit status of the last executed command. If the exit status is 0,  it prints “Division successful”; otherwise, prints “Error in division”.

return values in error handling

Since the denominator is 0, it displays an error message.

Common Issues with Bash Return Values

There are some problems that you may encounter while working with the bash function to return values. Let’s take a look at these problems and how to solve them.

Exceeding Return Value Limit

The return statement returns integer values between 0 and 255. Exceeding this range shows an unexpected result:

exceeding limit error

Here the value 9 is the remainder of 265 divided by 256. Actually, it resets to 0 after crossing the range. As an example, it yields 0 for 256, 1 for 257, and so forth. Likewise, it displays 9 for 265.

To avoid this problem and get the actual output, use the echo command or global variables:

The echo command with command substitution returns the value 265 as expected:

solution of exceeding limit error

Not Capturing Return Value

$? is used to capture the return value of the return statement. This must be used immediately after calling the function. If another command is called before the return value is captured, $? will be overwritten like this:

not capturing return value error

To solve this issue, write the $? immediately after the function has been called to capture the return value properly:

solution of not capturing return value error

As you can see in the image the actual return value 25 is displayed on the terminal.

Uninitialized Variable Error

If a variable is not initialized in the function, it can lead to an error:

unset variable value error

Since the local variable value is unset in the function, it displays the empty result. To solve this problem, initialize the variable value first:

solution of unset variable value error

Once the variable value has been set to 10, it will display the actual result.

Practice Tasks on Return Values from Bash Function

To improve your bash scripting skills and to understand how to return values from the bash function, practice the following:

  • Write a Bash script that defines a function add_numbers which takes two parameters, adds them, and returns the integer result.
  • Create a Bash script that defines a function is_even that takes a number as a parameter, and checks if it is even or odd.
  • Make a script where a function named reverse_string takes a string as a parameter, reverses it, and returns the reversed string.
  • Generate a script and create a function fibonacci that takes a number “n” as a parameter and returns the nth value in the Fibonacci sequence.

To conclude, I have covered the fundamentals of the bash function and how it returns values. Moreover, I have provided 6 examples of how to return values like integer, string, and array from the bash function. Some problems associated with returning values and their solutions are also explained. Lastly, don’t forget to complete the practice tasks. Have a great day!

People Also Ask

What is the return type and return value.

The return value is the value that a function produces when it finishes its execution. It is basically the result of the function and the data type of the return value is called the return type.

Do all functions return a value?

No. All functions don’t return a value. Whether a function returns value or not depends on the purposes of the function.

Can you call a void function?

Yes , you can call a void function. The void function is a function that does not return a value. So no return statement is required. At the end of a void function, it automatically returns to the caller.

Can a function only return once?

Actually, a function may have more than one return statement, but it returns a value the very first time it comes into contact with the return statement. When the function receives a return statement, it immediately exits and no more code is executed in the function. To execute multiple returns, you can use other approaches like using an array.

Can a function repeat itself?

Yes, a function in Bash can repeat itself using loops or recursive calls. Both for and while loops can be used for repeating a task within a function. Functions can also recursively call themselves.

Can functions return two values?

Yes, a function can return two values using a bash array and echo command. Here’s the example bash script:

Modify the code by replacing the values you want to return.

Mitu Akter Mou

Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

IMAGES

  1. How to use Variables in Bash

    bash variables list

  2. How to use Variables in Bash

    bash variables list

  3. What Are Bash Variables and How Can You Use Them?

    bash variables list

  4. Variables in Bash/Shell Scripts and How To Use Them [Tutorial]

    bash variables list

  5. Bash Variables

    bash variables list

  6. How to use Variables in Bash Programming

    bash variables list

VIDEO

  1. BASH PROGRAMMING (SYNTAX,VARIABLES AND OPERATORS)

  2. 003-Bash: Variables, Conditions, Loops

  3. Section-5: Vidoe-10 : Command Line Arguments to provide inputs for Variables of Bash Shell Script

  4. Linux BASH: Create Local Env Variables #shorts

  5. Imp Points To Develop Real-Time Bash Shell Scripts

  6. Geometry Bash 2 Trailer

COMMENTS

  1. How can I list all shell variables?

    1,724 3 16 32 A general warning related to most methods: When using such things in scripts, beware variables whose value contains a newline, e.g. IFS. Their representation in the output may span multiple lines. - Palec May 24, 2023 at 17:48 Add a comment 4 Answers Sorted by: 44 List all shell variables bash : use set -o posix ; set.

  2. How to list variables declared in script in bash?

    How to list variables declared in script in bash? Ask Question Asked 14 years, 6 months ago Modified 1 year, 6 months ago Viewed 110k times 124 In my script in bash, there are lot of variables, and I have to make something to save them to file. My question is how to list all variables declared in my script and get list like this:

  3. How to list all variables names and their current values?

    9 You've accepted an incorrect answer. "printenv" only gives you the environment variables. If you truly want all variables currently declared in your shell, use "declare -p" or "typeset -p". - Florin Andrei Jul 26, 2019 at 19:11 Add a comment 11 Answers Sorted by: 712 For bash: (the standard shell in Ubuntu)

  4. Bash Variables (Bash Reference Manual)

    A few variables used by Bash are described in different chapters: variables for controlling the job control facilities (see Job Control Variables ). _ ¶ ($_, an underscore.) At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list.

  5. How to Work with Variables in Bash

    Linux How to Work with Variables in Bash By Dave McKay Updated Aug 12, 2023 Want to take your Linux command-line skills to the next level? Here's everything you need to know to start working with variables. Hannah Stryker / How-To Geek Readers like you help support How-To Geek.

  6. How to Use Variables in Bash Shell Scripts

    echo "Hello, $name" Notice here, you have to precede the variable name with a dollar sign to get the value stored in the variable name. If you omit the dollar sign, "Hello, name" would be displayed instead. This dollar sign is known as the dereference operator in bash scripting. Integers, strings or characters?

  7. Check if a Variable Exists in a List in Bash

    In this tutorial, we saw three methods to check if a variable exists in a list. We first looked at using a simple for loop to iterate the list and verify if the item exists or not. Then, we piped the list separated with newlines through grep, and we used grep to check if a line matches the item.

  8. How to Use Arrays in Bash Shell Scripts

    Arrays to the rescue! So far, you have used a limited number of variables in your bash script, you have created a few variables to hold one or two filenames and usernames.. But what if you need more than a few variables in your bash scripts; let's say you want to create a bash script that reads a hundred different inputs from a user, are you going to create 100 variables?

  9. Bash Variables Explained: A Simple Guide With Examples

    Bash Local Variables . To create a variable, you need to assign a value to your variable name. Bash is an untyped language, so you don't have to indicate a data type when defining your variables. var1=Hello. Bash also allows multiple assignments on a single line: a=6 b=8 c=9

  10. How to Create a List in Bash Scripts? [2 Easy Methods]

    Method 1: Generate a List Using Loops in Bash Scripts In this method, you will see how to generate a list using for and while loops. Also, I have tried to make this list generation interactive, so that users can use it according to their needs. Case 1: List Files Using "for" Loop in Bash Script

  11. What Are Bash Variables and How to Work with Them on Linux

    Jan 16, 2024 Ignas R. 6min Read Bash Variables: Useful Methods for Working with Variables in Bash Any programming language comes with its own set of variables. They are an essential part of any system and are needed to run even the most simple programs.

  12. linux

    Here is a LIST: List = "abcd 1234 jvm something" How to get the second element "1234" without looping all the list? Stack Exchange Network. ... How to shorten a list of variable names in bash? 0. Bash script - How do I redirect output from a bash script to a file?

  13. Linux List All Environment Variables Command

    Fig.01: Command to see a list of all currently defined environment variables in a Linux bash terminal A list of the commonly used variables in Linux We use the printf command / echo command to display values of the shell varible in Linux. set and env command You can use the env / set command too: env env | more set set | more Sample outputs:

  14. How do I see a list of all currently defined environment variables in a

    According to the Bash manual you can use the set built-in command to show all of the environment variables that have been set. The set command will also display the definitions of any functions. If you only want to see the variables, and not the functions, then you can turn on POSIX mode before running the set command.

  15. How to List and Set Bash Environment Variables? [3 Methods]

    To list a specific Bash environment variable you can search for it from the list of environment variables, using the grep command. Now see the process practically by searching a specified variable, let's say, the PATH variable: #!/bin/bash #looking for the PATH variable in the environment variable list printenv | grep PATH EXPLANATION

  16. Special Variables in Bash Shell [With Script Examples]

    To get the name of the current script, you will have to utilize the #0 variable in your script with the echo. For example, here, I created a simple hello world program named Hello.sh which should reflect the filename while executing: #!/bin/bash echo "Hello from sagar" echo "Name of shell script = $0". And here's the output it gave while running:

  17. How to List Environment Variables on Linux

    To list environment variables on Linux, use the printenv command. That will show you all environment variables, but you can get searchable results by piping it into the less command. Alternatively, use grep to check specific environment variables. On Linux, environment variables hold important values and settings.

  18. How to Set and List Environment Variables in Linux

    Each shell such as zsh and bash, has its own set of internal shell variables. There are several commands available that allow you to list and set environment variables in Linux: env - The command allows you to run another program in a custom environment without modifying the current one.

  19. How to create a list and append values in bash script

    310 1 4 10 Add a comment 3 Answers Sorted by: 3 Here one idea/approach. #!/usr/bin/env bash arr= () while IFS= read -r val; do arr+= ("'$val'") done < < (printf '%s\n' 'foo bar' 'baz more' 'qux lux') (IFS=,; printf ' [%s]' "$ {arr [*]}") Output ['foo bar','baz more','qux lux'] Share Improve this answer Follow answered Nov 5, 2021 at 10:44

  20. How to Return Values From Function in Bash [6 Examples]

    To return other values like string or array, using echo command or global variables is a great way. 6 Examples of Return Values From Bash Function. In this section, how the bash function returns one value or multiple is discussed. Additionally, the bash function can return values as strings or arrays using echo command or global variables. Most ...

  21. bash

    In Bash, you can use: list=$(<test.txt) This uses the notation for command substitution but avoids the overhead of executing an external program. The non-Bash alternative is: list=$(cat test.txt) This also works in Bash, of course, but incurs the overhead of the separate cat process.. You can use back-quotes list=`cat test.txt` but you should generally use the $(…) notation instead.