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.

LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment > Bash Variable Naming Conventions in Shell Script [6 Rules]

Bash Variable Naming Conventions in Shell Script [6 Rules]

Mohammad Shah Miran

When writing shell scripts in Bash , choosing appropriate names for variables is essential for code readability and maintainability . By adhering to consistent naming conventions , you can enhance the clarity and understandability of your scripts, making them easier to debug and modify . This article will state some rules for Bash Variable naming conventions in the shell script .

Key Takeaways

  • Learning of Bash Variable Naming Conventions.
  • Creating your own variable name using the provided materials.
  • An assignment to test your understanding of the Variable Naming Convention.

Free Downloads

6 different bash variable naming conventions in shell script.

To build a comprehensive and easily understandable code, naming the variables with a proper guideline is crucial. This also allows one to avoid any unexpected errors occurring during Debugging time.

While Bash doesn’t enforce any strict naming conventions, developers often follow certain conventions to enhance code clarity and consistency. Down below, I have discussed six different rules that should be followed while choosing your variable name.

Rule 01: Naming a Variable Using Alphabets and Numbers

While alphabets are commonly used in variable names, incorporating numbers can add a level of specificity and clarity to your code. However, bash script is a case-sensitive language which means you can store different data in the same variable having different case combinations.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal .

❷ Write the following command to open a file in Nano :

  • nano : Opens a file in the Nano text editor.
  • var_alphabet.sh : Name of the file.

❸ Copy the script mentioned below:

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Then, there are three variables var , VAR , and var123 created to store some data in it. Later, the echo command was used to print their stored value to prove that all those variables’ naming are correct and in compliance with the bash script naming convention.

❹ Press CTRL+O and ENTER to save the file; CTRL + X exit.

❺ Use the following command to make the file executable:

  • chmod : is used to change the permissions of files and directories.
  • u+x : Here, u refers to the “ user ” or the owner of the file and +x specifies the permission being added, in this case, the “ execute ” permission. When u+x is added to the file permissions, it grants the user ( owner ) of the file permission to execute ( run ) the file.
  • var_alphabet.sh : is the name of the file to which the permissions are being applied.

❻ Run the script by the following command:

output image of Naming a Variable Using Alphabets and Numbers

Rule 02: Avoid Using Number at the Beginning of the Variable Name

When it comes to naming variables in Bash shell scripts, one important convention to follow is to avoid using a numeric digit as the first character of a variable name. Here is a sample example demonstrated below where I created several variables placing the number digit at the beginning and end of the variable name. The variable with the number digit at the beginning does not return its corresponding value in the execution time.

You can follow the steps of rule 01 , to save & make the script executable.

Script (var_number.sh) >

Here, #! /bin/bash : ‘ #! ’, is called shebang or hashbang . It indicates the interpreter to be used for executing the script, in this case, it’s bash . Next, a random variable 123var has been created by placing the number digit first. Another variable var123 is also named to show the correct way of naming. Later, the echo command displays the corresponding value contained in the variable.

output image of Avoid Using Number at the Beginning of the Variable Name

Rule 03: Using Underscore to Avoid Whitespace

If a variable name consists of multiple words , it is advisable to separate them using underscores (_). For instance, user_name is advisable instead of using username

Script (var_underscore.sh) >

The #!/bin/bash is called a shebang , and it specifies the interpreter (in this case, /bin/bash ) that should be used to execute the script. Next, the var_name variable is created and tried to display using the echo command . Similarly, another var_name variable is created to store a string inside it and displayed later.

output images of Using Underscore to Avoid Whitespace

Rule 04: No Whitespace on Either Side of the Assignment Operator(=)

When using this operator, it is recommended to have no whitespace (spaces or tabs) immediately before or after the operator. The interpreter takes it as a command instead of assigning value to the variable otherwise. Here is a relevant example stated below.

Script (var_whitespace.sh) >

Here, #! /bin/bash : ‘ #! ’, is called shebang or hashbang . It indicates the interpreter to be used for executing the script, in this case, it’s bash . Then a variable var1 is created and a whitespace is there followed by the var1 . In the case of the second variable, var2 , there is another whitespace followed by the equal sign . Both cases are wrong and thus will occur an error in execution time. Later another variable var3 has been created in the correct way and then displayed with the echo command .

output image without using Whitespace on Either Side of the Assignment Operator(=) | bash variable naming conventions in shell script

Rule 05: Avoiding Special Characters (Except Underscore)

In general, it is best to stick to alphanumeric characters ( letters and numbers ) and underscores when naming variables. Avoid using special characters , whitespace , or punctuation marks, as they can cause syntax errors or introduce unexpected behaviour. For instance, using any special character such as @, $, or # anywhere while declaring a variable is not legal.

Script (var_special_character.sh) >

Here, #! /bin/bash : ‘ #! ’, is called shebang or hashbang . It indicates the interpreter to be used for executing the script, in this case, it’s bash . Next, three different variables are created using special characters such as @, #, $. Next, all three variables are called using the echo command to display their individual data. Later, another variable var is also created and displayed using the echo command .

output image by Avoiding Special Characters | bash variable naming conventions in shell script

Rule 06: Avoid Reserved Keywords or Built-in Command Names as Variable Names

Bash has a set of reserved keywords that have special meanings and functionalities within the shell. Although you will get the variable data, to prevent conflicts and unexpected behaviour, it is crucial to avoid using these reserved keywords as variable names. Examples of reserved keywords include if , else , case , do , while, etc.

Script (var_Reserved_keyword.sh) >

Here, #! /bin/bash : ‘ #! ’, is called shebang or hashbang . It indicates the interpreter to be used for executing the script, in this case, it’s bash . Some reserved words such as while , if , elif , etc store data in this code. Then it displays the value using the echo command .

output image by Avoiding Reserved Keywords or Built-in Command Names as Variable Names | bash variable naming conventions in shell script

Comparison of Correct and Incorrect Variable Naming Conventions

Lastly, I draw a summary of the discussion in a table to describe the permissible and non-permissible ways to name the variable. Check this out to get the overall view.

Assignment on Bash Variable Naming Convention

Here I have also made a list of assignments to practice by yourself. Don’t forget to share your answer in the comment section.

  • Using uppercase letters in variable names is acceptable. (True/False)
  • We can use hyphens (-) in variable names in Bash . (True/False)
  • Bash is case-sensitive, so myVar and myvar are considered different variables. (True/False)
  • We can use Whitespace in variable names in Bash. (True/False)
  • Variable names can contain special characters like !, @, and # in Bash. (True/False)
  • Provide a valid variable name in Bash that includes both uppercase and lowercase letters, as well as an underscore .
  • Determine whether the following variable names are correct or not :
  • My variable

In conclusion, adhering to proper variable naming conventions is essential when working with Bash variables in shell scripts. In this article, I have tried to give you some must known rules to follow while choosing your variable name. Things are easy if you remember however if you have any query related to this article. Feel free to comment below. Thank you.

People Also Ask

Related Articles

  • How to Declare Variable in Bash Scripts? [5 Practical Cases]
  • How to Assign Variables in Bash Script? [8 Practical Cases]
  • How to Check Variable Value Using Bash Scripts? [5 Cases]
  • How to Use Default Value in Bash Scripts? [2 Methods]
  • How to Use Set – $Variable in Bash Scripts? [2 Examples]
  • How to Read Environment Variables in Bash Script? [2 Methods]
  • How to Export Environment Variables with Bash? [4 Examples]

<< Go Back to Variable Declaration and Assignment  | Bash Variables | Bash Scripting Tutorial

Mohammad Shah Miran

Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment Cancel reply

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

linuxsimply white logo

Get In Touch!

card

Legal Corner

dmca

Copyright © 2024 LinuxSimply | All Rights Reserved.

Special Characters

What makes a character special? If it has a meaning beyond its literal meaning , a meta-meaning, then we refer to it as a special character. Along with commands and keywords, special characters are building blocks of Bash scripts.

Special Characters Found In Scripts and Elsewhere

Command separator [semicolon] . Permits putting two or more commands on the same line.

echo hello; echo there

if [ -x "$filename" ]; then # Note the space after the semicolon. #+ ^^ echo "File $filename exists."; cp $filename $filename.bak else # ^^ echo "File $filename not found."; touch $filename fi; echo "File test complete."

Note that the ";" sometimes needs to be escaped .

Terminator in a case option [double semicolon] .

Comments . Lines beginning with a # (with the exception of #!) are comments and will not be executed.

Comments may also occur following the end of a command.

Comments may also follow whitespace at the beginning of a line.

Comments may even be embedded within a pipe.

Caution: A command may not follow a comment on the same line. There is no method of terminating the comment, in order for "live code" to begin on the same line. Use a new line for the next command.

A quoted or an escaped # in an echo statement does not begin a comment. Likewise, a # appears in certain parameter-substitution constructs and in numerical constant expressions.

echo "The # here does not begin a comment." echo 'The # here does not begin a comment.' echo The \# here does not begin a comment. echo The # here begins a comment.

echo ${PATH#*:} # Parameter substitution, not a comment. echo $(( 2#101011 )) # Base conversion, not a comment.

# Thanks, S.C.

The standard quoting and escape characters (" ' \) escape the #.

Certain pattern matching operations also use the #.

"dot", as a component of a filename . When working with filenames, a leading dot is the prefix of a "hidden" file, a file that an ls will not normally show.

bash$ touch .hidden-file bash$ ls -l total 10 -rw-r--r-- 1 bozo 4034 Jul 18 22:04 data1.addressbook -rw-r--r-- 1 bozo 4602 May 25 13:58 data1.addressbook.bak -rw-r--r-- 1 bozo 877 Dec 17 2000 employment.addressbook

bash$ ls -al total 14 drwxrwxr-x 2 bozo bozo 1024 Aug 29 20:54 ./ drwx------ 52 bozo bozo 3072 Aug 29 20:51 ../ -rw-r--r-- 1 bozo bozo 4034 Jul 18 22:04 data1.addressbook -rw-r--r-- 1 bozo bozo 4602 May 25 13:58 data1.addressbook.bak -rw-r--r-- 1 bozo bozo 877 Dec 17 2000 employment.addressbook -rw-rw-r-- 1 bozo bozo 0 Aug 29 20:54 .hidden-file

When considering directory names, a single dot represents the current working directory, and two dots denote the parent directory.

bash$ pwd /home/bozo/projects

bash$ cd . bash$ pwd /home/bozo/projects

bash$ cd .. bash$ pwd /home/bozo/

The dot often appears as the destination (directory) of a file movement command, in this context meaning current directory .

Copy all the "junk" files to $PWD .

comma operator . The comma operator [1] links together a series of arithmetic operations. All are evaluated, but only the last one is returned.

The comma operator can also concatenate strings.

for file in /{,usr/}bin/*calc # ^ Find all executable files ending in "calc" #+ in /bin and /usr/bin directories. do if [ -x "$file" ] then echo $file fi done

# /bin/ipcalc # /usr/bin/kcalc # /usr/bin/oidcalc # /usr/bin/oocalc

# Thank you, Rory Winston, for pointing this out.

escape [backslash] . A quoting mechanism for single characters.

\X escapes the character X. This has the effect of "quoting" X, equivalent to 'X'. The \ may be used to quote " and ', so they are expressed literally.

Filename path separator [forward slash] . Separates the components of a filename (as in /home/bozo/projects/Makefile ).

This is also the division arithmetic operator .

null command [colon] . This is the shell equivalent of a "NOP" ( no op , a do-nothing operation). It may be considered a synonym for the shell builtin true . The ":" command is itself a Bash builtin , and its exit status is true (0).

Endless loop:

while : do operation-1 operation-2 ... operation-n done

# Same as: # while true # do # ... # done

Placeholder in if/then test:

Provide a placeholder where a binary operation is expected

: ${username=`whoami`} # ${username=`whoami`} Gives an error without the leading : # unless "username" is a command or builtin...

: ${1?"Usage: $0 ARGUMENT"} # From "usage-message.sh example script.

Provide a placeholder where a command is expected in a here document .

Evaluate string of variables using parameter substitution.

Variable expansion / substring replacement .

In combination with the > redirection operator, truncates a file to zero length, without changing its permissions. If the file did not previously exist, creates it.

: > data.xxx # File "data.xxx" now empty.

# Same effect as cat /dev/null >data.xxx # However, this does not fork a new process, since ":" is a builtin.

In combination with the >> redirection operator, has no effect on a pre-existing target file (: >> target_file) . If the file did not previously exist, creates it.

Note: This applies to regular files, not pipes, symlinks, and certain special files.

May be used to begin a comment line, although this is not recommended. Using # for a comment turns off error checking for the remainder of that line, so almost anything may appear in a comment. However, this is not the case with :.

The ":" serves as a field separator, in /etc/passwd , and in the $PATH variable.

A colon is acceptable as a function name.

:() { echo "The name of this function is "$FUNCNAME" " # Why use a colon as a function name? # It's a way of obfuscating your code. }

# The name of this function is :

This is not portable behavior, and therefore not a recommended practice. In fact, more recent releases of Bash do not permit this usage. An underscore _ works, though.

A colon can serve as a placeholder in an otherwise empty function.

reverse (or negate) the sense of a test or exit status [bang] . The ! operator inverts the exit status of the command to which it is applied. It also inverts the meaning of a test operator. This can, for example, change the sense of equal ( = ) to not-equal ( != ). The ! operator is a Bash keyword.

In a different context, the ! also appears in indirect variable references .

In yet another context, from the command line , the ! invokes the Bash history mechanism (see Appendix L). Note that within a script, the history mechanism is disabled.

wild card [asterisk] . The * character serves as a "wild card" for filename expansion in globbing . By itself, it matches every filename in a given directory.

The * also represents any number (or zero) characters in a regular expression .

arithmetic operator . In the context of arithmetic operations, the * denotes multiplication.

** A double asterisk can represent the exponentiation operator or extended file-match globbing .

test operator . Within certain expressions, the ? indicates a test for a condition.

In a double-parentheses construct , the ? can serve as an element of a C-style trinary operator . [2]

Format: condition?result-if-true:result-if-false

(( var0 = var1<98?9:21 )) # ^ ^

# if [ "$var1" -lt 98 ] # then # var0=9 # else # var0=21 # fi

In a parameter substitution expression, the ? tests whether a variable has been set.

Variable substitution (contents of a variable) .

var1=5 var2=23skidoo

echo $var1 # 5 echo $var2 # 23skidoo

A $ prefixing a variable name indicates the value the variable holds.

command group .

Important: A listing of commands within parentheses starts a subshell .

Variables inside parentheses, within the subshell, are not visible to the rest of the script. The parent process, the script, cannot read variables created in the child process , the subshell.

a=123 ( a=321; )

echo "a = $a" # a = 123 # "a" within parentheses acts like a local variable.

array initialization.

Brace expansion.

echo \"{These,words,are,quoted}\" # " prefix and suffix # "These" "words" "are" "quoted"

cat {file1,file2,file3} > combined_file # Concatenates the files file1, file2, and file3 into combined_file.

cp file22.{txt,backup} # Copies "file22.txt" to "file22.backup"

A command may act upon a comma-separated list of file specs within braces (The shell does the brace expansion. The command itself acts upon the result of the expansion.) Filename expansion, known as globbing , applies to the file specs between the braces.

Caution: No spaces allowed within the braces unless the spaces are quoted or escaped.

echo {file1,file2}\ :{\A," B",' C'}

file1 : A file1 : B file1 : C file2 : A file2 : B file2 : C

Extended Brace expansion.

echo {a..z} # a b c d e f g h i j k l m n o p q r s t u v w x y z # Echoes characters between a and z.

echo {0..3} # 0 1 2 3 # Echoes characters between 0 and 3.

base64_charset=( {A..Z} {a..z} {0..9} + / = ) # Initializing an array, using extended brace expansion. # From vladz's "base64.sh" example script.

The { a..z } extended brace expansion construction is a feature introduced in version 3 of Bash.

Block of code [curly brackets] . Also referred to as an inline group , this construct, in effect, creates an anonymous function (a function without a name). However, unlike in a "standard" function , the variables inside a code block remain visible to the remainder of the script.

bash$ { local a; a=123; } bash: local: can only be used in a function

a=123 { a=321; } echo "a = $a" # a = 321 (value inside code block)

The code block enclosed in braces may have I/O redirected to and from it.

Code blocks and I/O redirection

#!/bin/bash # Reading lines in /etc/fstab.

File=/etc/fstab

{ read line1 read line2 } < $File

echo "First line in $File is:" echo "$line1" echo echo "Second line in $File is:" echo "$line2"

# Now, how do you parse the separate fields of each line? # Hint: use awk, or . . . # . . . Hans-Joerg Diers suggests using the "set" Bash builtin.

Saving the output of a code block to a file

#!/bin/bash # rpm-check.sh

# Queries an rpm file for description, listing, #+ and whether it can be installed. # Saves output to a file. # # This script illustrates using a code block.

SUCCESS=0 E_NOARGS=65

if [ -z "$1" ] then echo "Usage: `basename $0` rpm-file" exit $E_NOARGS fi

{ # Begin code block. echo echo "Archive Description:" rpm -qpi $1 # Query description. echo echo "Archive Listing:" rpm -qpl $1 # Query listing. echo rpm -i --test $1 # Query whether rpm file can be installed. if [ "$?" -eq $SUCCESS ] then echo "$1 can be installed." else echo "$1 cannot be installed." fi echo # End code block. } > "$1.test" # Redirects output of everything in block to file.

echo "Results of rpm test in file $1.test"

# See rpm man page for explanation of options.

Unlike a command group within (parentheses), as above, a code block enclosed by { braces } will not normally launch a subshell.

Exception: a code block in braces as part of a pipe may run as a subshell.

ls | { read firstline; read secondline; } # Error. The code block in braces runs as a subshell, #+ so the output of "ls" cannot be passed to variables within the block. echo "First line is $firstline; second line is $secondline" # Won't work.

It is possible to iterate a code block using a non-standard for-loop .

placeholder for text. Used after xargs -i (replace strings option). The { } double curly brackets are a placeholder for output text.

ls . | xargs -i -t cp ./{} $1 # ^^ ^^

# From "ex42.sh" (copydir.sh) example.

pathname . Mostly used in find constructs. This is not a shell builtin .

Definition: A pathname is a filename that includes the complete path . As an example, /home/bozo/Notes/Thursday/schedule.txt . This is sometimes referred to as the absolute path .

The ";" ends the -exec option of a find command sequence. It needs to be escaped to protect it from interpretation by the shell.

array element . In the context of an array , brackets set off the numbering of each element of that array.

integer expansion . Evaluate integer expression between $[ ].

echo $[$a+$b] # 10 echo $[$a*$b] # 21

Note that this usage is deprecated, and has been replaced by the (( ... )) construct.

redirection .

scriptname >filename redirects the output of scriptname to file filename . Overwrite filename if it already exists.

command &>filename redirects both the stdout and the stderr of command to filename .

This is useful for suppressing output when testing for a condition. For example, let us test whether a certain command exists.

bash$ type bogus_command &>/dev/null

bash$ echo $? 1

Or in a script:

command_test () { type "$1" &>/dev/null; } # ^

cmd=rmdir # Legitimate command. command_test $cmd; echo $? # 0

cmd=bogus_command # Illegitimate command command_test $cmd; echo $? # 1

command >&2 redirects stdout of command to stderr .

scriptname >>filename appends the output of scriptname to file filename . If filename does not already exist, it is created.

[i]<>filename opens file filename for reading and writing, and assigns file descriptor i to it. If filename does not exist, it is created.

process substitution .

(command)>

<(command)

In a different context, the "<" and ">" characters act as string comparison operators .

In yet another context, the "<" and ">" characters act as integer comparison operators

ASCII comparison .

veg1=carrots veg2=tomatoes

if [[ "$veg1" < "$veg2" ]] then echo "Although $veg1 precede $veg2 in the dictionary," echo -n "this does not necessarily imply anything " echo "about my culinary preferences." else echo "What kind of dictionary are you using, anyhow?" fi

word boundary in a regular expression .

pipe . Passes the output ( stdout ) of a previous command to the input ( stdin ) of the next one, or to the shell. This is a method of chaining commands together.

echo ls -l | sh # Passes the output of "echo ls -l" to the shell, #+ with the same result as a simple "ls -l".

cat *.lst | sort | uniq # Merges and sorts all ".lst" files, then deletes duplicate lines.

A pipe, as a classic method of interprocess communication, sends the stdout of one process to the stdin of another. In a typical case, a command, such as cat or echo , pipes a stream of data to a filter , a command that transforms its input for processing. [5]

For an interesting note on the complexity of using UNIX pipes, see the UNIX FAQ, Part 3 .

The output of a command or commands may be piped to a script.

#!/bin/bash # uppercase.sh : Changes input to uppercase.

tr 'a-z' 'A-Z' # Letter ranges must be quoted #+ to prevent filename generation from single-letter filenames.

Now, let us pipe the output of ls -l to this script.

The stdout of each process in a pipe must be read as the stdin of the next. If this is not the case, the data stream will block , and the pipe will not behave as expected.

A pipe runs as a child process , and therefore cannot alter script variables.

If one of the commands in the pipe aborts, this prematurely terminates execution of the pipe. Called a broken pipe , this condition sends a SIGPIPE signal .

Run job in background . A command followed by an & will run in the background.

Within a script, commands and even loops may run in the background.

Running a loop in the background

#!/bin/bash # background-loop.sh

for i in 1 2 3 4 5 6 7 8 9 10 # First loop. do echo -n "$i " done & # Run this loop in background. # Will sometimes execute after second loop.

echo # This 'echo' sometimes will not display.

for i in 11 12 13 14 15 16 17 18 19 20 # Second loop. do echo -n "$i " done

# ======================================================

# The expected output from the script: # 1 2 3 4 5 6 7 8 9 10 # 11 12 13 14 15 16 17 18 19 20

# Sometimes, though, you get: # 11 12 13 14 15 16 17 18 19 20 # 1 2 3 4 5 6 7 8 9 10 bozo $ # (The second 'echo' doesn't execute. Why?)

# Occasionally also: # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # (The first 'echo' doesn't execute. Why?)

# Very rarely something like: # 11 12 13 1 2 3 4 5 6 7 8 9 10 14 15 16 17 18 19 20 # The foreground loop preempts the background one.

# Nasimuddin Ansari suggests adding sleep 1 #+ after the echo -n "$i" in lines 6 and 14, #+ for some real fun.

Caution: A command run in the background within a script may cause the script to hang, waiting for a keystroke. Fortunately, there is a remedy for this.

option, prefix . Option flag for a command or filter. Prefix for an operator. Prefix for a default parameter in parameter substitution .

COMMAND -[Option1][Option2][...]

sort -dfu $filename

if [ $file1 -ot $file2 ] then # ^ echo "File $file1 is older than $file2." fi

if [ "$a" -eq "$b" ] then # ^ echo "$a is equal to $b." fi

if [ "$c" -eq 24 -a "$d" -eq 47 ] then # ^ ^ echo "$c equals 24 and $d equals 47." fi

param2=${param1:-$DEFAULTVAL} # ^

redirection from/to stdin or stdout [dash] .

bash$ cat - abc abc

As expected, cat - echoes stdin , in this case keyboarded user input, to stdout . But, does I/O redirection using "-" have real-world applications?

(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -) # Move entire file tree from one directory to another # [courtesy Alan Cox <[email protected]>, with a minor change]

# 1) cd /source/directory # Source directory, where the files to be moved are. # 2) && # "And-list": if the 'cd' operation successful, # then execute the next command. # 3) tar cf - . # The 'c' option 'tar' archiving command creates a new archive, # the 'f' (file) option, followed by '-' designates the target file # as stdout, and do it in current directory tree ('.'). # 4) | # Piped to ... # 5) ( ... ) # a subshell # 6) cd /dest/directory # Change to the destination directory. # 7) && # "And-list", as above # 8) tar xpvf - # Unarchive ('x'), preserve ownership and file permissions ('p'), # and send verbose messages to stdout ('v'), # reading data from stdin ('f' followed by '-'). # # Note that 'x' is a command, and 'p', 'v', 'f' are options. # # Whew!

# More elegant than, but equivalent to: # cd source/directory # tar cf - . | (cd ../dest/directory; tar xpvf -) # # Also having same effect: # cp -a /source/directory/* /dest/directory # Or: # cp -a /source/directory/* /source/directory/.[^.]* /dest/directory # If there are hidden files in /source/directory.

Note that in this context the "-" is not itself a Bash operator, but rather an option recognized by certain UNIX utilities that write to stdout , such as tar , cat , etc.

Where a filename is expected, "-" redirects output to stdout (sometimes seen with tar cf ), or accepts input from stdin , rather than from a file. This is a method of using a file-oriented utility as a filter in a pipe.

By itself on the command-line, file fails with an error message.

Add a "-" for a more useful result. This causes the shell to await user input.

bash$ file - abc standard input: ASCII text

bash$ file - #!/bin/bash standard input: Bourne-Again shell script text executable

Now the command accepts input from stdin and analyzes it.

The "-" can be used to pipe stdout to other commands. This permits such stunts as prepending lines to a file.

Using diff to compare a file with a section of another:

grep Linux file1 | diff file2 -

Finally, a real-world example using "-" with tar .

Backup of all files changed in last day

#!/bin/bash

# Backs up all files in current directory modified within last 24 hours #+ in a "tarball" (tarred and gzipped file).

BACKUPFILE=backup-$(date +%m-%d-%Y) # Embeds date in backup filename. # Thanks, Joshua Tschida, for the idea. archive=${1:-$BACKUPFILE} # If no backup-archive filename specified on command-line, #+ it will default to "backup-MM-DD-YYYY.tar.gz."

tar cvf - `find . -mtime -1 -type f -print` > $archive.tar gzip $archive.tar echo "Directory $PWD backed up in archive file \"$archive.tar.gz\"."

# Stephane Chazelas points out that the above code will fail #+ if there are too many files found #+ or if any filenames contain blank characters.

# He suggests the following alternatives: # ------------------------------------------------------------------- # find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar" # using the GNU version of "find".

# find . -mtime -1 -type f -exec tar rvf "$archive.tar" '{}' \; # portable to other UNIX flavors, but much slower. # -------------------------------------------------------------------

Caution: Filenames beginning with "-" may cause problems when coupled with the "-" redirection operator. A script should check for this and add an appropriate prefix to such filenames, for example ./-FILENAME , $PWD/-FILENAME , or $PATHNAME/-FILENAME .

If the value of a variable begins with a "-", this may likewise create problems.

The double-dash -- prefixes long (verbatim) options to commands.

sort --ignore-leading-blanks

Used with a Bash builtin, it means the end of options to that particular command.

Tip: This provides a handy means of removing files whose names begin with a dash.

bash$ ls -l -rw-r--r-- 1 bozo bozo 0 Nov 25 12:29 -badname

bash$ rm -- -badname

bash$ ls -l total 0

The double-dash is also used in conjunction with set .

set -- $variable

previous working directory . A cd - command changes to the previous working directory. This uses the $OLDPWD environmental variable.

Caution: Do not confuse the "-" used in this sense with the "-" redirection operator just discussed. The interpretation of the "-" depends on the context in which it appears.

Equals . Assignment operator

In a different context, the "=" is a string comparison operator.

Plus . Addition arithmetic operator.

In a different context, the "+" is a Regular Expression operator.

Option . Option flag for a command or filter.

Certain commands and builtins use the "+" to enable certain options and the "-" to disable them. In parameter substitution, the "+" prefixes an alternate value that a variable expands to.

modulo . Modulo (remainder of a division) arithmetic operation.

In a different context, the "%" is a pattern matching operator.

home directory [tilde] . This corresponds to the $HOME internal variable. ~bozo is bozo's home directory, and ls ~bozo lists the contents of it. ~/ is the current user's home directory, and ls ~/ lists the contents of it.

bash$ echo ~bozo /home/bozo

bash$ echo ~ /home/bozo

bash$ echo ~/ /home/bozo/

bash$ echo ~: /home/bozo:

bash$ echo ~nonexistent-user ~nonexistent-user

change the behavior of the terminal or text display . A control character is a CONTROL + key combination (pressed simultaneously). A control character may also be written in octal or hexadecimal notation, following an escape .

Control characters are not normally useful inside a script.

  • Ctrl-A Moves cursor to beginning of line of text (on the command-line).
  • Ctrl-B Backspace (nondestructive).
  • Ctrl-C Break . Terminate a foreground job.

Ctrl-D Log out from a shell (similar to exit ).

EOF (end-of-file). This also terminates input from stdin .

When typing text on the console or in an xterm window, Ctrl-D erases the character under the cursor. When there are no characters present, Ctrl-D logs out of the session, as expected. In an xterm window, this has the effect of closing the window.

  • Ctrl-E Moves cursor to end of line of text (on the command-line).
  • Ctrl-F Moves cursor forward one character position (on the command-line).
  • Ctrl-G BEL . On some old-time teletype terminals, this would actually ring a bell. In an xterm it might beep.

Ctrl-H Rubout (destructive backspace). Erases characters the cursor backs over while backspacing.

#!/bin/bash # Embedding Ctrl-H in a string.

a="^H^H" # Two Ctrl-H's -- backspaces # ctl-V ctl-H, using vi/vim echo "abcdef" # abcdef echo echo -n "abcdef$a " # abcd f # Space at end ^ ^ Backspaces twice. echo echo -n "abcdef$a" # abcdef # No space at end ^ Doesn't backspace (why?). # Results may not be quite as expected. echo; echo

# Constantin Hagemeier suggests trying: # a=$'\010\010' # a=$'\b\b' # a=$'\x08\x08' # But, this does not change the results.

########################################

# Now, try this.

rubout="^H^H^H^H^H" # 5 x Ctrl-H.

echo -n "12345678" sleep 2 echo -n "$rubout" sleep 2

  • Ctrl-I Horizontal tab.
  • Ctrl-J Newline (line feed). In a script, may also be expressed in octal notation -- '\012' or in hexadecimal -- '\x0a'.
  • Ctrl-K Vertical tab. When typing text on the console or in an xterm window, Ctrl-K erases from the character under the cursor to end of line. Within a script, Ctrl-K may behave differently, as in Lee Lee Maschmeyer's example, below.
  • Ctrl-L Formfeed (clear the terminal screen). In a terminal, this has the same effect as the clear command. When sent to a printer, a Ctrl-L causes an advance to end of the paper sheet.

Ctrl-M Carriage return .

#!/bin/bash # Thank you, Lee Maschmeyer, for this example.

read -n 1 -s -p \ $'Control-M leaves cursor at beginning of this line. Press Enter. \x0d' # Of course, '0d' is the hex equivalent of Control-M. echo >&2 # The '-s' makes anything typed silent, #+ so it is necessary to go to new line explicitly.

read -n 1 -s -p $'Control-J leaves cursor on next line. \x0a' # '0a' is the hex equivalent of Control-J, linefeed. echo >&2

read -n 1 -s -p $'And Control-K\x0bgoes straight down.' echo >&2 # Control-K is vertical tab.

# A better example of the effect of a vertical tab is:

var=$'\x0aThis is the bottom line\x0bThis is the top line\x0a' echo "$var" # This works the same way as the above example. However: echo "$var" | col # This causes the right end of the line to be higher than the left end. # It also explains why we started and ended with a line feed -- #+ to avoid a garbled screen.

# As Lee Maschmeyer explains: # -------------------------- # In the [first vertical tab example] . . . the vertical tab #+ makes the printing go straight down without a carriage return. # This is true only on devices, such as the Linux console, #+ that can't go "backward." # The real purpose of VT is to go straight UP, not down. # It can be used to print superscripts on a printer. # The col utility can be used to emulate the proper behavior of VT.

  • Ctrl-N Erases a line of text recalled from history buffer [6] (on the command-line).
  • Ctrl-O Issues a newline (on the command-line).
  • Ctrl-P Recalls last command from history buffer (on the command-line).
  • Ctrl-Q Resume ( XON ). This resumes stdin in a terminal.
  • Ctrl-R Backwards search for text in history buffer (on the command-line).
  • Ctrl-S Suspend ( XOFF ). This freezes stdin in a terminal. (Use Ctrl-Q to restore input.)
  • Ctrl-T Reverses the position of the character the cursor is on with the previous character (on the command-line).
  • Ctrl-U Erase a line of input, from the cursor backward to beginning of line. In some settings, @kbd{Ctrl-U} erases the entire line of input, regardless of cursor position.

Ctrl-V When inputting text, Ctrl-V permits inserting control characters. For example, the following two are equivalent:

Ctrl-V is primarily useful from within a text editor.

  • Ctrl-W When typing text on the console or in an xterm window, Ctrl-W erases from the character under the cursor backwards to the first instance of whitespace . In some settings, Ctrl-W erases backwards to first non-alphanumeric character.
  • Ctrl-X In certain word processing programs, Cuts highlighted text and copies to clipboard .
  • Ctrl-Y Pastes back text previously erased (with Ctrl-U or Ctrl-W ).
  • Ctrl-Z Pauses a foreground job.
  • Ctrl-Z Substitute operation in certain word processing applications.
  • Ctrl-Z EOF (end-of-file) character in the MSDOS filesystem.

functions as a separator between commands and/or variables . Whitespace consists of either spaces, tabs, blank lines, or any combination thereof. [7] In some contexts, such as variable assignment, whitespace is not permitted, and results in a syntax error.

Blank lines have no effect on the action of a script, and are therefore useful for visually separating functional sections.

$IFS , the special variable separating fields of input to certain commands. It defaults to whitespace.

Definition: A field is a discrete chunk of data expressed as a string of consecutive characters. Separating each field from adjacent fields is either whitespace or some other designated character (often determined by the $IFS ). In some contexts, a field may be called a record.

To preserve whitespace within a string or in a variable, use quoting.

UNIX filters can target and operate on whitespace using the POSIX character class [:space:].

Previous: Positional Parameters , Up: Shell Parameters   [ Contents ][ Index ]

3.4.2 Special Parameters

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.

($*) Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word. In contexts where it is performed, those words are subject to further word splitting and filename expansion. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1 c $2 c …" , where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

($@) Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parameter to a separate word; if not within double quotes, these words are subject to word splitting. In contexts where word splitting is not performed, this expands to a single word with each positional parameter separated by a space. When the expansion occurs within double quotes, and word splitting is performed, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" … . If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

($#) Expands to the number of positional parameters in decimal.

($?) Expands to the exit status of the most recently executed foreground pipeline.

($-, a hyphen.) Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option).

($$) Expands to the process ID of the shell. In a subshell, it expands to the process ID of the invoking shell, not the subshell.

($!) Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin (see Job Control Builtins ).

($0) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see Shell Scripts ), $0 is set to the name of that file. If Bash is started with the -c option (see Invoking Bash ), then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.

How-To Geek

15 special characters you need to know for bash.

That sequence of strange symbols on the Bash command line must mean something, right? We're breaking down special characters and how to use them.

Quick Links

What are special characters, ~ home directory, . current directory, .. parent directory, / path directory separator, # comment or trim strings, single character bash wildcard, * character sequence bash wildcard, [] character set wildcard, ; shell command separator, & background process, < input redirection, > output redirection, pipeline logical not and history operator, $ variable expressions, quoting special characters, key takeaways.

  • Special characters often function like command short-hand, and tell Bash to perform a specific function without having to type out a longer, more verbose command.
  • The tilde (~) refers to the home directory, double periods (..) refers to the parent directory, and a single period (.) refers to the current directory.
  • Other important characters / for directory separation, # for comments, ? for wildcard characters, ; for separating commands, and | for piping commands together.

If you want to master the Bash shell on Linux, macOS, or another UNIX-like system, special characters (like ~, *, |, and >) are critical. We'll help you unravel these cryptic Linux command sequences and become a hero of hieroglyphics.

There are a set of characters the Bash shell treats in two different ways. When you type them at the shell, they act as instructions or commands and tell the shell to perform a certain function. Think of them as single-character commands.

Sometimes, you just want to print a character and don't need it to act as a magic symbol. There's a way you can use a character to represent itself rather than its special function.

We'll show you which characters are "special" or "meta-" characters, as well as how you can use them functionally and literally.

The tilde (~) is shorthand for your home directory. It means you don't have to type the full path to your home directory in commands. Wherever you are in the filesystem, you can use this command to go to your home directory:

You can also use this command with relative paths. For example, if you're somewhere in the file system that's not under your home folder and want to change to the archive directory in your work directory, use the tilde to do it:

cd ~/work/archive

A period (.) represents the current directory. You see it in directory listings if you use the -a (all) option with ls .

You can also use the period in commands to represent the path to your current directory. For example, if you want to run a script from the current directory, you would call it like this:

./script.sh

This tells Bash to look in the current directory for the script.sh file. This way, it won't search the directories in your path for matching executable or script.

The double period or "double dot" (..) represents the parent directory of your current one. You can use this to move up one level in the directory tree.

You can also use this command with relative paths---for example, if you want to go up one level in the directory tree, and then enter another directory at that level.

You can also use this technique to move quickly to a directory at the same level in the directory tree as your current one. You hop up one level, and then back down one into a different directory.

cd ../gc_help

You can use a forward-slash (/)---often just called a slash---to separate the directories in a pathname.

ls ~/work/archive

One forward-slash represents the shortest possible directory path. Because everything in the Linux directory tree starts at the root directory, you can use this command to move to the root directory quickly:

Most often, you use the hash or number sign (#) to tell the shell what follows is a comment, and it should not act on it. You can use it in shell scripts and---less usefully---on the command line.

# This will be ignored by the Bash shell

It isn't truly ignored, however, because it's added to your command history.

You can also use the hash to trim a string variable and remove some text from the beginning. This command creates a string variable called this_string .

In this example, we assign the text "Dave Geek!" to the variable.

this_string="Dave Geek!"

This command uses echo to print the words "How-To" to the terminal window. It retrieves the value stored in the string variable via a parameter expansion . Because we append the hash and the text "Dave," it trims off that portion of the string before it's passed to echo .

echo How-To ${this_string#Dave}

This doesn't change the value stored in the string variable; it only affects what's sent to echo . We can use echo to print the value of the string variable once more and check this:

echo $this_string

Bash shell supports three wildcards, one of which is the question mark (?). You use wildcards to replace characters in filename templates. A filename that contains a wildcard forms a template that matches a range of filenames, rather than just one.

The question mark wildcard represents exactly one character. Consider the following filename template:

ls badge?.txt

This translates as "list any file with a name that starts with 'badge' and is followed by any single character before the filename extension."

It matches the following files. Note that some have numbers and some have letters after the "badge" portion of the filename. The question mark wildcard will match both letters and numbers.

That filename template doesn't match "badge.txt," though, because the filename doesn't have a single character between "badge" and the file extension. The question mark wildcard must match a corresponding character in the filename.

You can also use the question mark to find all files with a specific number of characters in the filenames. This lists all text files that contain exactly five characters in the filename:

ls ?????.txt

You can use the asterisk (*) wildcard to stand for any sequence of characters, including no characters. Consider the following filename template:

This matches all of the following:

It matches "badge.txt" because the wildcard represents any sequence of characters or no characters.

This command matches all files called "source," regardless of the file extension.

ls source.*

As covered above, you use the question mark to represent any single character and the asterisk to represent any sequence of characters (including no characters).

You can form a wildcard with the square brackets ( [] ) and the characters they contain. The relevant character in the filename must then match at least one of the characters in the wildcard character set.

In this example, the command translates to: "any file with a ".png" extension, a filename beginning with "pipes_0," and in which the next character is either 2, 4, or 6."

ls badge_0[246].txt

You can use more than one set of brackets per filename template:

ls badge_[01][789].txt

You can also include ranges in the character set. The following command selects files with the numbers 21 to 25, and 31 to 35 in the filename.

ls badge_[23][1-5].txt

You can type as many commands as you like on the command line, as long as you separate each of them with a semicolon (;). We'll do this in the following example:

ls > count.txt; wc -l count.txt; rm count.txt

Note that the second command runs even if the first fails, the third runs even if the second fails, and so on.

If you want to stop the sequence of execution if one command fails, use a double ampersand (&&) instead of a semicolon:

cd ./doesntexist && cp ~/Documents/reports/* .

After you type a command in a terminal window and it completes, you return to the command prompt. Normally, this only takes a moment or two. But if you launch another application, such as gedit , you cannot use your terminal window until you close the application.

You can, however, launch an application as a background process and continue to use the terminal window. To do this, just add an ampersand to the command line:

gedit command_address.page &

Bash shows you the process ID of what launched, and then returns you to the command line. You can then continue to use your terminal window.

Many Linux commands accept a file as a parameter and take their data from that file. Most of these commands can also take input from a stream. To create a stream, you use the left-angle bracket ( < ), as shown in the following example, to redirect a file into a command:

sort < words.txt

When a command has input redirected into it, it might behave differently than when it reads from a named file.

If we use wc to count the words, lines, and characters in a file, it prints the values, and then the filename. If we redirect the contents of the file to wc , it prints the same numeric values but doesn't know the name of the file from which the data came. It cannot print a filename.

Here are some examples of how you can use wc :

wc words.txt

wc < words.txt

You can use the right-angle bracket ( > ) to redirect the output from a command (typically, into a file); here's an example:

ls > files.txt

cat files.txt

Output redirection can also redirect error messages if you use a digit (2, in our example) with > . Here's how to do it:

wc doesntexist.txt 2> errors.txt

cat errors.txt

A "pipe" chains commands together. It takes the output from one command and feeds it to the next as input. The number of piped commands (the length of the chain) is arbitrary.

Here, we'll use cat to feed the contents of the words.txt file into grep , which extracts any line that contains either a lower- or uppercase "C." grep will then pass these lines to sort . sort is using the -r (reverse) option, so the sorted results will appear in reverse order.

We typed the following:

cat words.txt | grep [cC] | sort -r

The exclamation point (!) is a logical operator that means NOT.

There are two commands in this command line:

[ ! -d ./backup ] && mkdir ./backup

  • The first command is the text within the square brackets;
  • The second command is the text that follows the double ampersands && .

The first command uses ! as a logical operator. The square brackets indicate a test is going to be made. The -d (directory) option tests for the presence of a directory called backup. The second command creates the directory.

Because double ampersands separate the two commands, Bash will only execute the second if the first succeeds. However, that's the opposite of what we need. If the test for the "backup" directory succeeds, we don't need to create it. And if the test for the "backup "directory fails, the second command won't be executed, and the missing directory won't be created.

This is where the logical operator ! comes in. It acts as a logical NOT. So, if the test succeeds (i.e., the directory exists), the ! flips that to "NOT success," which is failure. So, the second command isn't activated.

If the directory test fails (i.e., the directory doesn't exist), the ! changes the response to "NOT failure," which is success. So, the command to create the missing directory is executed.

That little ! packs a lot of punch when you need it to!

To check the status of the backup folder, you use the ls command and the -l (long listing) and -d (directory) options, as shown below:

ls -l -d backup

You can also run commands from your command history with the exclamation point. The history command lists your command history, and you then type the number of the command you wish to re-run with ! to execute it, as shown below:

The following re-runs the previous command:

In the Bash shell, you create variables to hold values. Some, like environment variables, always exist, and you can access them any time you open a terminal window. These hold values, such as your username, home directory, and path.

You can use echo to see the value a variable holds---just precede the variable name with the dollar sign ($), as shown below:

To create a variable, you must give it a name and provide a value for it to hold. You do not have to use the dollar sign to create a variable. You only add $ when you reference a variable, such as in the following example:

ThisDistro=Ubuntu

MyNumber=2001

echo $ThisDistro

echo $MyNumber

Add braces ( {} ) around the dollar sign and perform a parameter expansion to obtain the value of the variable and allow further transformations of the value.

This creates a variable that holds a string of characters, as shown below:

MyString=123456qwerty

Use the following command to echo the string to the terminal window:

echo ${MyString}

To return the substring starting at position 6 of the whole string, use the following command (there's a zero-offset, so the first position is zero):

echo ${myString:6}

If you want to echo a substring that starts at position zero and contains the next six characters, use the following command:

echo ${myString:0:6}

Use the following command to echo a substring that starts at position four and contains the next four characters:

echo ${myString:4:4}

If you want to use a special character as a literal (non-special) character, you have to tell the Bash shell. This is called quoting, and there are three ways to do it.

If you enclose the text in quotation marks ("..."), this prevents Bash from acting on most of the special characters, and they just print. One notable exception, though, is the dollar sign ($). It still functions as the character for variable expressions, so you can include the values from variables in your output.

For example, this command prints the date and time:

echo "Today is $(date)"

If you enclose the text in single quotes ('...') as shown below, it stops the function of all the special characters:

echo 'Today is $(date)'

You can use a backslash ( \ ) to prevent the following character from functioning as a special character. This is called "escaping" the character; see the example below:

echo "Today is \$(date)"

Just think of special characters as very short commands. If you memorize their uses, it can benefit your understanding of the Bash shell---and other people's scripts---immensely.

How-to: Default Shell variables and bash variables

Shell and environment variables:.

The shell maintains a list of variables, each of which has as value a list of zero or more words. The values of shell variables can be displayed and changed with the echo , set and unset commands. The system maintains its own list of 'environment' variables. These can be displayed and changed with printenv , setenv and unsetenv . (+) Variables may be made read-only with set -r (q.v.) Read-only variables may not be modified or unset; attempting to do so will cause an error. Once made read-only, a variable cannot be made writable, so set -r should be used with caution. Environment variables cannot be made read-only. Some variables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell’s argument list, and words of this variable’s value are referred to in special ways. Some of the variables referred to by the shell are toggles; the shell does not care what their value is, only whether they are set or not. For instance, the verbose variable is a toggle which causes command input to be echoed. The -v command line option sets this variable. Special shell variables lists all variables which are referred to by the shell.

Default Shell Variables

Bash automatically assigns default values to a number of variables, which are listed below. Bash uses the 10 shell variables below in the same way as the Bourne shell. Variable Description CDPATH A colon-separated list of directories used as a search path for the cd builtin command. HOME The current user’s home directory; the default for the cd builtin command. The value of this variable is also used by tilde expansion. IFS A list of characters that separate fields (Internal Field Separator or Input Field Separator) used when the shell splits words as part of expansion. By default this is set to Space, Tab and Newline. IFS= (or IFS='' ) will prevent leading/trailing whitespace from being trimmed when using read . To set this to Newline only, use IFS=$'\n' MAIL If this parameter is set to a filename and the MAILPATH variable is not set, Bash informs the user of the arrival of mail in the specified file. MAILPATH A colon-separated list of filenames which the shell periodically checks for new mail. Each list entry can specify the message that is printed when new mail arrives in the mail file by separating the file name from the message with a '?' . When used in the text of the message, $_ expands to the name of the current mail file. OPTARG The value of the last option argument processed by the getopts builtin. OPTIND The index of the last option argument processed by the getopts builtin. PATH A colon-separated list of directories in which the shell looks for commands. PS1 The primary prompt string . PS2 The secondary prompt string . The default value is '> '

Bash Variables

These variables are set or used by Bash, but other shells do not normally treat them specially. Variable Description _ ($_, 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. BASH The full pathname used to execute the current instance of Bash. BASHOPTS 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. 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. BASHPID 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. BASH_ALIASES 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. BASH_ARGC 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 command 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. BASH_ARGV 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 command 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. BASH_ARGV0 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. BASH_CMDS An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin. 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. BASH_COMMAND 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. BASH_COMPAT 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. 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_EXECUTION_STRING The command argument to the -c invocation option. BASH_LINENO 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. BASH_LOADABLES_PATH A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command. BASH_REMATCH An array variable whose members are assigned by the ‘ =~ ’ binary operator to the [[ conditional command . 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. BASH_SOURCE 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]} BASH_SUBSHELL 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. BASH_VERSINFO 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: BASH_VERSINFO[0] The major version number (the release). BASH_VERSINFO[1] The minor version number (the version). BASH_VERSINFO[2] The patch level. BASH_VERSINFO[3] The build version. BASH_VERSINFO[4] The release status (e.g., beta1). BASH_VERSINFO[5] The value of MACHTYPE. BASH_VERSION The version number of the current instance of Bash. BASH_XTRACEFD 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. CHILD_MAX 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. COLUMNS 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 . COMP_CWORD 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 ). COMP_LINE The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ). COMP_POINT 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 ). COMP_TYPE 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 ). COMP_KEY The key (or final key of a key sequence) used to invoke the current completion function. COMP_WORDBREAKS 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. COMP_WORDS 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 ). COMPREPLY 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. COPROC An array variable created to hold the file descriptors for output from and input to an unnamed coprocess (see Coprocesses ). DIRSTACK 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. EMACS 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. ENV Expanded and executed similarlty to BASH_ENV (see Bash Startup Files ) when an interactive shell is invoked in POSIX Mode (see Bash POSIX Mode ). EPOCHREALTIME 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. EPOCHSECONDS 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. EUID The numeric effective user id of the current user. This variable is readonly. EXECIGNORE 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. FCEDIT The editor used as a default by the -e option to the fc builtin command. FIGNORE 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:~ ’ FUNCNAME 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. FUNCNEST 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. GLOBIGNORE 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. GROUPS 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. histchars 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. HISTCMD 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. HISTCONTROL 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 . 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. 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. HISTIGNORE 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 . HISTSIZE 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. HISTTIMEFORMAT 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. 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. 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. 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. 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. INPUTRC The name of the Readline initialization file, overriding the default of ~/.inputrc . INSIDE_EMACS 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 . 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 filename expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching (see Filename Expansion ). LC_CTYPE This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching (see Filename Expansion ). LC_MESSAGES This variable determines the locale used to translate double-quoted strings preceded by a ‘ $ ’ (see Locale Translation ). LC_NUMERIC This variable determines the locale category used for number formatting. LC_TIME This variable determines the locale category used for data and time formatting. LINENO 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. LINES 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 . 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. 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. MAPFILE An array variable created to hold the text read by the mapfile builtin when no variable name is supplied. OLDPWD The previous working directory as set by the cd builtin. OPTERR If set to the value 1, Bash displays error messages generated by the getopts builtin command. OSTYPE A string describing the Operating System Bash is running on. PIPESTATUS 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). POSIXLY_CORRECT If this variable is in the environment when Bash starts, the shell enters 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 set -o posix had been executed. When the shell enters POSIX mode, it sets this variable if it was not already set. PPID The process ID of the shell’s parent process. This variable is readonly. PROMPT_COMMAND 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. PROMPT_DIRTRIM 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. PS0 The value of this parameter is expanded like PS1 and displayed by interactive shells after reading a command and before the command is executed. PS3 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 ‘ #? ’ PS4 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 ‘ + ’. PWD The current working directory as set by the cd builtin. RANDOM 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. READLINE_LINE The contents of the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtins ). READLINE_MARK The position of the mark (saved insertion point) in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtins ). The characters between the insertion point and the mark are often called the region . READLINE_POINT The position of the insertion point in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtins ). REPLY The default variable for the read builtin. SECONDS 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 is always determined by querying the system clock. If SECONDS is unset, it loses its special properties, even if it is subsequently reset. SHELL 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. SHELLOPTS 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. 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. SHLVL 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. SRANDOM 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. TIMEFORMAT %% A literal '%' %[p][l]R The elapsed time in seconds. %[p][l]U The number of CPU seconds spent in user mode. %[p][l]S The number of CPU seconds spent in system mode. %P The CPU percentage, computed as (%U + %S) / %R. 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.     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 $'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS' If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed. TMOUT If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin (see Bash Builtins ). The select command (see the if , case and test 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. TMPDIR If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell’s use. UID The numeric real user id of the current user. This variable is readonly.

To read any variable prefix it with $

To add or modify a system wide environment variable, there are two main ways to do this, using launchctl setenv or by directly editing the file /etc/launchd.conf and adding some setenv commands. Both approaches will require a reboot.

Before rushing to do this consider carefully if it is needed, launchd.conf does not exist by default, it is easy to break dependencies if you change a variable used by other programs. If setting a variable in the user environment will suffice, then set a shell variable by adding an export command to your startup file .

Related Linux commands

Arguments - bash shell parameters. export - Set an environment variable. local - Create a function variable. env - Display, set, or remove environment variables. printenv - Print environment variables. Bash syntax Windows PowerShell equivalent: Variables - Creating and reading environment variables. gnu.org Bash-Variables - Full list.

IMAGES

  1. The Bash Special Characters You Should Know About

    bash variable assignment special characters

  2. Bash Variable Naming Conventions in Shell Script [6 Rules]

    bash variable assignment special characters

  3. How to Use Special Variables in Bash

    bash variable assignment special characters

  4. Special Bash Variables with examples

    bash variable assignment special characters

  5. The Bash Special Characters You Should Know About

    bash variable assignment special characters

  6. The Bash Special Characters You Should Know About

    bash variable assignment special characters

VIDEO

  1. Working with BASH shell

  2. Our Vison for VoteBash in 2025 with Martijn Atell

  3. Video Assignment Special Issues Irfan Ismail

  4. 6 storing values in variable, assignment statement

  5. How to get values for variables from a source file using Bash Script on Rocky Linux 9.2

  6. && and || Linux Bash command chaining operators

COMMENTS

  1. How do I use a variable with special characters in bash?

    How to check if a variable is set in Bash Hot Network Questions A short YA SF novel about teenagers who lived their whole childhood in a house surrounded by a fence in a clearing of a "dangerous forest"

  2. 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".

  3. How to Work with Variables in Bash

    Here, we'll create five variables. The format is to type the name, the equals sign =, and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable. We'll create four string variables and one numeric variable, my_name=Dave.

  4. Special Variables in Bash [With 9 Practical Examples]

    The special variables $1, $2, $3, … $9 contain the first nine command-line arguments provided to the script. Here, each variable corresponds to a specific positional number like $1 represents the first argument, $2 represents the second argument, etc. Here's an example of the special variables $1, $2, and $3: #!/bin/bash.

  5. Special Bash Variables with examples

    The special $* variable is a shorthand for writing all variables into a single string. Let's see how this works by defining a new test2.sh script as follows:. echo "1: ${1}" echo "2: ${2}" echo "All: ${*}" As a slight variation, we chose to define our variables here as ${1} to ${*} instead of $1 to $*.In fact, it would be a good idea to always quote variables this way.

  6. Bash Variables Explained: A Simple Guide With Examples

    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. ... In its simplest form, it uses the special character $ followed by the variable name (with no spaces in between): var6=Jack echo My ...

  7. Bash Variables (Bash Reference Manual)

    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. BASH_CMDS ¶

  8. How to Use Variables in Bash Shell Scripts

    Using variables in bash shell scripts. In the last tutorial in this series, you learned to write a hello world program in bash. #! /bin/bash echo 'Hello, World!'. That was a simple Hello World script. Let's make it a better Hello World. Let's improve this script by using shell variables so that it greets users with their names.

  9. Bash Special Variables

    Then, we can invoke positional_variables, passing it two parameters: So far, there's nothing special about this handling. Let's try to reference an argument that was not passed: echo "Positional variable 1: ${1}" echo "Positional variable 2: ${2}" echo "Positional variable 3: ${3}" Bash considers it unassigned: 2.1.

  10. Mastering Variable Assignment In Bash: Syntax, Manipulation, Scopes

    Basic Syntax for Assigning Variables in Bash. In Bash scripting, assigning variables is a fundamental concept that allows you to store and manipulate data. Understanding the basic syntax for assigning variables is crucial for writing effective Bash scripts. In this section, we will explore the different ways to assign values to variables in ...

  11. Bash Variable Naming Conventions in Shell Script [6 Rules]

    The variable with the number digit at the beginning does not return its corresponding value in the execution time. You can follow the steps of rule 01, to save & make the script executable. Script (var_number.sh) >. #!/bin/bash. #variable with number first (invalid way) 123var="Wrong Way to name". #correct way.

  12. Special Characters

    Along with commands and keywords, special characters are building blocks of Bash scripts. Special Characters Found In Scripts and Elsewhere; ... The `command` construct makes available the output of command for assignment to a variable. This is also known as backquotes or backticks.:

  13. How to store and print variables with special characters in shell/bash

    That's where basic good practices such as always quoting your variables (see Why does my shell script choke on whitespace or other special characters? and Security implications of forgetting to quote a variable in bash/POSIX shells) and using the standard --to indicate the end of options whenever you call a program and pass it a variable as ...

  14. Special Parameters (Bash Reference Manual)

    When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c…", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces.

  15. 15 Special Characters You Need to Know for Bash

    echo 'Today is $(date)'. You can use a backslash ( \ ) to prevent the following character from functioning as a special character. This is called "escaping" the character; see the example below: echo "Today is \$(date)" Just think of special characters as very short commands.

  16. List of acceptable initial characters for a bash variable

    Name s are used as shell variable and function names. Also referred to as an identifier. (That's the definition in Bash's manual, POSIX probably has something similar.) So, anything that matches the regex [a-zA-Z_][a-zA-Z_0-9]* (assuming ASCII character ranges) is a valid name for a variable. Unicode characters and punctuation don't work.

  17. How-To: bash Shell variables

    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. BASH_CMDS

  18. Chapter 3. Special Characters

    Along with commands and keywords , special characters are building blocks of Bash scripts. Special Characters Found In Scripts and Elsewhere. #. Comments. Lines beginning with a # (with the exception of #!) are comments and will not be executed. # This line is a comment.

  19. set the group variable in azure devops pipeline using bash script

    Variable values need to be formatted correctly before being passed as multi-line variables. When formatting your variable, avoid special characters, don't use restricted names, and make sure you use a line ending format that works for the operating system of your agent. Multi-line variables behave differently depending on the operating system.