nixCraft

How To Use Bash Parameter Substitution Like A Pro

bash variable assignment substitution

T he $ character is used for parameter expansion, arithmetic expansion and command substitution. You can use it for manipulating and expanding variables on demands without using external commands such as perl, python, sed or awk. This guide shows you how to use parameter expansion modifiers to transform Bash shell variables for your scripting needs.

How To Use Bash Parameter Substitution Like A Pro

1. Setting Up Default Shell Variables Value

The syntax is as follows:

If parameter not set, use defaultValue . In this example, your shell script takes arguments supplied on the command line. You’d like to provide default value so that the most common value can be used without needing to type them every time. If variable $1 is not set or passed, use root as default value for u:

Consider the following example:

You can now run this script as follows:

Here is another handy example:

Use this substitution for creating failsafe functions and providing missing command line arguments in scripts.

#1.1: Setting Default Values

The assignment operator (:=) is used to assign a value to a variable. If the variable doesn’t already have a value, it will be given the new one. Here are some examples:

Sample outputs:

Now, assign a value foo to the $myUSER variable if doesn’t already have one:

Unset value for $myUSER:

This make sure you always have a default reasonable value for your variable in a shell script. Try:

Tip: ${var:-defaultValue} vs ${var:=defaultValue}

Please note that it will not work with positional parameter arguments:

The var="${1:=defaultValue}" will generate an error thar read as follows:

However, the var="${1:-defaultValue}" will work.

2. Display an Error Message If $VAR Not Passed

If the variable is not defined or not passed, you can stop executing the Bash script with the following syntax:

This is used for giving an error message for unset parameters. In this example, if the $1 command line arg is not passed, stop executing the script with an error message:

Here is a sample script:

2.1. Display an Error Message and Run Command

If $2 is not set display an error message for $2 parameter and run cp command on fly as follows:

3. Find Variable Length

You can easily find string length using the following syntax:

Here is a sample shell script to add a ftp user:

Each Linux or UNIX command returns a status when it terminates normally or abnormally. You can use command exit status in the shell script to display an error message or take some sort of action. In above example, if getent command is successful, it returns a code which tells the shell script to display an error message. 0 exit status means the command was successful without any errors. $? holds the return value set by the previously executed command.

4. Remove Pattern (Front of $VAR)

You can strip $var as per given pattern from front of $var. In this example remove /etc/ part and get a filename only, enter:

We see the file name:

The first syntax removes shortest part of pattern and the second syntax removes the longest part of the pattern. Consider the following example:

You just want to get filename i.e. dnstop-20090128.tar.gz, enter (try to remove shortest part of $_url) :

Now try using the longest part of the pattern syntax:

This is also useful to get a script name without using /bin/basename:

Create a script called master.info as follows:

Finally, create a new softlink as follows : $ sudo ln -s master.info uploaddir.info $ sudo ln -s master.info tmpdir.info $ sudo ln -s master.info mem.info .... .. You can now call script as follows: $ sudo ./mem.info cyberciti.biz $ ./cpu.info cyberciti.biz nixcraft.com

#4.1: Remove Pattern (Back of $VAR)

Exactly the same as above, except that it applies to the back of $var. In this example remove .tar.gz from $FILE, enter:

Here is what I get:

Rename all *.perl files to *.pl using bash for loop as Apache web server is configured to only use .pl file and not .perl file names:

You can combine all of them as follows to create a build scripts :

If you turn on nocasematch option , shell matches patterns in a case-insensitive fashion when performing matching while executing case or [[ conditional expression .

5. Find And Replace

Find word unix and replace with linux, enter:

You can avoid using sed as follows:

To replace all matches of pattern, enter :

You can use this to rename or remove files on fly

Here is another example:

The following function installs required modules in chrooted php-cgi process

6. Substring Starting Character

Expands to up to length characters of parameter starting at the character specified by offset.

Extract craft word only:

To extract phone number, enter:

7. Get list of matching variable names

Want to get the names of variables whose names begin with prefix? Try:

Bash get list of all the variables whose names match a certain prefix

8. Convert to upper to lower case or vice versa

Use the following syntax to convert lowercase characters to uppercase:

Bash shell case conversion

See “ Shell Scripting: Convert Uppercase to Lowercase ” for more info.

Summary: String Manipulation and Expanding Variables

Table 1: Bash Parameter Substitution
Variable Description
Get default shell variables value
Set default shell variables value
Display an error message if parameter is not set
Find the length of the string
Remove from shortest rear (end) pattern
Remove from longest rear (end) pattern
Substring
Remove from shortest front pattern
Remove from longest front pattern
Find and replace (only replace first occurrence)
Find and replace all occurrences
Expands to the names of variables whose names begin with prefix.

Convert first character to lowercase.

Convert all characters to lowercase.

Convert first character to uppercase.

Convert all character to uppercase.

References:

Do read bash man page using the man command or help command : $ man bash $ help command-name-here

  • Improve your bash/sh shell script with ShellCheck lint script analysis tool
  • Linux shell scripting wiki
  • oo-style string library for bash 4
  • Bash man page

🥺 Was this helpful? Please add a comment to show your appreciation or feedback .

nixCrat Tux Pixel Penguin

Category List of Unix and Linux commands
Ansible
Archiving
Backup Management
Database Server
Download managers
Driver Management
Documentation
Disk Management
File Management
Firewall
KVM Virtualization
Linux Desktop apps
LXD
Modern utilities
Network Management
Network Utilities
OpenVPN
Power Management
Package Manager
Processes Management
Searching
Shell builtins
System Management
Terminal/ssh
Text processing
Text Editor
User Environment
User Information
User Management
Web Server
WireGuard VPN

I hate to go offtopic, but do you know if these apply to tcsh as well?

Vivek Gite (Author and Admin)

I’ve not used tcsh / csh much; but should work with ksh. HTH

These are POSIX shell expansions and bash/ksh93 extensions. They do not apply to tcsh (which should not be used for scripting).

I hate to go offtopic as well, but I love the Internet Explorer 9 ad on the right….. wtf?

Ads comes from various sources. This is the only way to cover the cost of hosting, CDN and bandwidth. Hope this helps!

So you got post back but deleted all comments? How come?

Backups are done ones a day. This post was restored from my local open office org cache file. There is not much I can do to restore all 12-13 comments including yours.

What a great tutorial and reference. I can never remember the syntax when I need it. Will definitely be bookmarking this one.

Great tips! There are some functionalities I didn’t even know existed.

cp “${y}” “${y/.conf/.conf.bak}”

a more simple approach:

cp “${y}”{,.bak}

Or, more portably and efficiently:

cp ${y,.bak}

In bash, a comma in parameter expansion converts to lower case:

You’re right. Not sure where my brain was that day. One would I assume I tested it before commenting, but it doesn’t seem to do anything. No error or warning either. That’s bash for you. 😛

There’s no reason for any error message or warning; it’s a perfectly legal, if nonsensical, expansion.

Man, did I need this today. Thanks!

very useful,like this site very much

good tutorial,

Thanks for this excellent HowTo! One minor correction: sed ‘s/unix/linux’ <<<$x should be sed 's/unix/linux/g' <<<$x

Otherwise you get an unterminated `s' command error.

Thanks for the heads up!

on the bash-shell-parameter-substitution-2.html page, _mkdir() example, fourth line you write: [ $# -eq 0 ] &shouldn’t this be [ $# -eq 0 ] &## [0—] is four digit octal permissions

or equivalent to allow user to set permissions other than the default 0755 value?

prior message was strangely truncated in places. Resubmit:

on the bash-shell-parameter-substitution-2.html page, _mkdir() example, fourth line you write:

[ $# -eq 0 ] &shouldn’t this be:

[ $# -eq 0 ] &## [0—] is four digit octal permissions

to inform user to set permissions other than the default 0755 value if desired?

Last attempt: on the bash-shell-parameter-substitution-2.html page, _mkdir() example, 4th line: [ $# -eq 0 ] &shouldn’t this be: [ $# -eq 0 ] &## [0—] is octal permissions to inform user to set other than the default 0755 value if desired?

Nice! learnt something from this tutorial..

Something interesting to note on the substring syntax is that you can address the offset backwards as well. I am not sure about how portable this syntax is, but I have found it very useful:

echo “${VAR: -4}” # Prints the last 4 characters, note the space between : and – in this example.

echo “${VAR:1:-1}” # The space is optional on the second offset, but not the first

${bam:=value} -bash: value: command not found

@khoan, yes, what did you expect? There is no command named ‘value’. Put echo in front and it should output ‘value’ unless $bam is already set.

Just what i wanted to learn. Thanks!

How much does that apply to “dash”?

Ikem, all the POSIX expansions (#1..#4) will work in dash (but not the shopt command).

… aaaaand BOOKMARKED. *punches Command+D* Thanks for the helpful reference! 😀

Superb post! Bookmarked. This is the type of content I was looking for while learning bash scripting.

Glad you found it useful.

Hi, some examples won’t work under bash version 4 For example ${var^^} Cheers

Really insightful. Bookmarked. Thanks a lot!

Please don’t use this:

> printf “$dest\n”

Always use something like this:

> printf “%s\n” “$dest”

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Next post: Download Fedora 14 CD / DVD ISO

Previous post: Download Ubuntu 10.10 (Maverick Meerkat) CD ISO / DVD Images

🔥 FEATURED ARTICLES

  • 1 30 Cool Open Source Software I Discovered in 2013
  • 2 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
  • 3 Top 32 Nmap Command Examples For Linux Sys/Network Admins
  • 4 25 PHP Security Best Practices For Linux Sys Admins
  • 5 30 Linux System Monitoring Tools Every SysAdmin Should Know
  • 6 40 Linux Server Hardening Security Tips
  • 7 Linux: 25 Iptables Netfilter Firewall Examples For New SysAdmins
  • 8 Top 20 OpenSSH Server Best Security Practices
  • 9 Top 25 Nginx Web Server Best Security Practices
  • 10 My 10 UNIX Command Line Mistakes
  • ➔ Howtos & Tutorials
  • ➔ Linux shell scripting tutorial
  • ➔ About nixCraft

Next: Command Substitution , Previous: Tilde Expansion , Up: Shell Expansions   [ Contents ][ Index ]

3.5.3 Shell Parameter Expansion

The ‘ $ ’ character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.

When braces are used, the matching ending brace is the first ‘ } ’ not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion.

The basic form of parameter expansion is ${ parameter }. The value of parameter is substituted. The parameter is a shell parameter as described above (see Shell Parameters ) or an array reference (see Arrays ). The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character that is not to be interpreted as part of its name.

If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new parameter ; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter . This is known as indirect expansion . The value is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${! prefix *} and ${! name [@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

When not performing substring expansion, using the form described below (e.g., ‘ :- ’), Bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter ’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

If parameter is unset or null, the expansion of word is assigned to parameter . The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.

If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

This is referred to as Substring Expansion. It expands to up to length characters of the value of parameter starting at the character specified by offset . If parameter is ‘ @ ’ or ‘ * ’, an indexed array subscripted by ‘ @ ’ or ‘ * ’, or an associative array name, the results differ as described below. If length is omitted, it expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see Shell Arithmetic ).

If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter . If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘ :- ’ expansion.

Here are some examples illustrating substring expansion on parameters and subscripted arrays:

If parameter is ‘ @ ’ or ‘ * ’, the result is length positional parameters beginning at offset . A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is an expansion error if length evaluates to a number less than zero.

The following examples illustrate substring expansion using positional parameters:

If parameter is an indexed array name subscripted by ‘ @ ’ or ‘ * ’, the result is the length members of the array beginning with ${ parameter [ offset ]} . A negative offset is taken relative to one greater than the maximum index of the specified array. It is an expansion error if length evaluates to a number less than zero.

These examples show how you can use substring expansion with indexed arrays:

Substring expansion applied to an associative array produces undefined results.

Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default. If offset is 0, and the positional parameters are used, $0 is prefixed to the list.

Expands to the names of variables whose names begin with prefix , separated by the first character of the IFS special variable. When ‘ @ ’ is used and the expansion appears within double quotes, each variable name expands to a separate word.

If name is an array variable, expands to the list of array indices (keys) assigned in name . If name is not an array, expands to 0 if name is set and null otherwise. When ‘ @ ’ is used and the expansion appears within double quotes, each key expands to a separate word.

The length in characters of the expanded value of parameter is substituted. If parameter is ‘ * ’ or ‘ @ ’, the value substituted is the number of positional parameters. If parameter is an array name subscripted by ‘ * ’ or ‘ @ ’, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter , so negative indices count back from the end of the array, and an index of -1 references the last element.

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching ). If the pattern matches the beginning of the expanded value of parameter , then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘ # ’ case) or the longest matching pattern (the ‘ ## ’ case) deleted. If parameter is ‘ @ ’ or ‘ * ’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘ @ ’ or ‘ * ’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching ). If the pattern matches a trailing portion of the expanded value of parameter , then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘ % ’ case) or the longest matching pattern (the ‘ %% ’ case) deleted. If parameter is ‘ @ ’ or ‘ * ’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘ @ ’ or ‘ * ’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string . string undergoes tilde expansion, parameter and variable expansion, arithmetic expansion, command and process substitution, and quote removal. The match is performed according to the rules described below (see Pattern Matching ).

In the first form above, only the first match is replaced. If there are two slashes separating parameter and pattern (the second form above), all matches of pattern are replaced with string . If pattern is preceded by ‘ # ’ (the third form above), it must match at the beginning of the expanded value of parameter . If pattern is preceded by ‘ % ’ (the fourth form above), it must match at the end of the expanded value of parameter . If the expansion of string is null, matches of pattern are deleted. If string is null, matches of pattern are deleted and the ‘ / ’ following pattern may be omitted.

If the patsub_replacement shell option is enabled using shopt , any unquoted instances of ‘ & ’ in string are replaced with the matching portion of pattern . This is intended to duplicate a common sed idiom.

Quoting any part of string inhibits replacement in the expansion of the quoted portion, including replacement strings stored in shell variables. Backslash will escape ‘ & ’ in string ; the backslash is removed in order to permit a literal ‘ & ’ in the replacement string. Users should take care if string is double-quoted to avoid unwanted interactions between the backslash and double-quoting, since backslash has special meaning within double quotes. Pattern substitution performs the check for unquoted ‘ & ’ after expanding string , so users should ensure to properly quote any occurrences of ‘ & ’ they want to be taken literally in the replacement and ensure any instances of ‘ & ’ they want to be replaced are unquoted.

For instance,

will display four lines of "abc def", while

will display four lines of "& def". Like the pattern removal operators, double quotes surrounding the replacement string quote the expanded characters, while double quotes enclosing the entire parameter substitution do not, since the expansion is performed in a context that doesn’t take any enclosing double quotes into account.

Since backslash can escape ‘ & ’, it can also escape a backslash in the replacement string. This means that ‘ \\ ’ will insert a literal backslash into the replacement, so these two echo commands

will both output ‘ \abcxyzdef ’.

It should rarely be necessary to enclose only string in double quotes.

If the nocasematch shell option (see the description of shopt in The Shopt Builtin ) is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is ‘ @ ’ or ‘ * ’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘ @ ’ or ‘ * ’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

This expansion modifies the case of alphabetic characters in parameter . The pattern is expanded to produce a pattern just as in filename expansion. Each character in the expanded value of parameter is tested against pattern , and, if it matches the pattern, its case is converted. The pattern should not attempt to match more than one character.

The ‘ ^ ’ operator converts lowercase letters matching pattern to uppercase; the ‘ , ’ operator converts matching uppercase letters to lowercase. The ‘ ^^ ’ and ‘ ,, ’ expansions convert each matched character in the expanded value; the ‘ ^ ’ and ‘ , ’ expansions match and convert only the first character in the expanded value. If pattern is omitted, it is treated like a ‘ ? ’, which matches every character.

If parameter is ‘ @ ’ or ‘ * ’, the case modification operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘ @ ’ or ‘ * ’, the case modification operation is applied to each member of the array in turn, and the expansion is the resultant list.

The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator . Each operator is a single letter:

The expansion is a string that is the value of parameter with lowercase alphabetic characters converted to uppercase.

The expansion is a string that is the value of parameter with the first character converted to uppercase, if it is alphabetic.

The expansion is a string that is the value of parameter with uppercase alphabetic characters converted to lowercase.

The expansion is a string that is the value of parameter quoted in a format that can be reused as input.

The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'…' quoting mechanism.

The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see Controlling the Prompt ).

The expansion is a string in the form of an assignment statement or declare command that, if evaluated, will recreate parameter with its attributes and value.

Produces a possibly-quoted version of the value of parameter , except that it prints the values of indexed and associative arrays as a sequence of quoted key-value pairs (see Arrays ).

The expansion is a string consisting of flag values representing parameter ’s attributes.

Like the ‘ K ’ transformation, but expands the keys and values of indexed and associative arrays to separate words after word splitting.

If parameter is ‘ @ ’ or ‘ * ’, the operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘ @ ’ or ‘ * ’, the operation is applied to each member of the array in turn, and the expansion is the resultant list.

The result of the expansion is subject to word splitting and filename expansion as described below.


On-line Guides

How To Guides

  




 

 

Chapter 4. Introduction to Variables and Parameters

4.1. Variable Substitution

The name of a variable is a placeholder for its value , the data it holds. Referencing its value is called variable substitution .

Let us carefully distinguish between the name of a variable and its value . If variable1 is the name of a variable, then $variable1 is a reference to its value , the data item it contains. The only time a variable appears "naked" -- without the $ prefix -- is when declared or assigned, when unset , when exported , or in the special case of a variable representing a signal (see Example 29-5 ). Assignment may be with an = (as in var1=27 ), in a read statement, and at the head of a loop ( for var2 in 1 2 3 ).

Enclosing a referenced value in double quotes ( " " ) does not interfere with variable substitution. This is called partial quoting , sometimes referred to as "weak quoting." Using single quotes ( ' ' ) causes the variable name to be used literally, and no substitution will take place. This is full quoting , sometimes referred to as "strong quoting." See Chapter 5 for a detailed discussion.

Note that $variable is actually a simplified alternate form of ${variable} . In contexts where the $variable syntax causes an error, the longer form may work (see Section 9.3 , below).

Example 4-1. Variable assignment and substitution

An uninitialized variable has a "null" value - no assigned value at all (not zero!). Using a variable before assigning a value to it will usually cause problems.

It is nevertheless possible to perform arithmetic operations on an uninitialized variable.

Introduction to Variables and Parameters Variable Assignment

bash variable assignment substitution

  Published under the terms of the GNU General Public License   

bash variable assignment substitution

How to Do Bash Variable Substitution (Parameter Substitution)

When the original value of any expression is substituted by another value then it is called substitution. Bash variable substitution or parameter substitution is a very useful feature of bash. Generally, it is done in the bash by using the '$' character and the optional curly brackets ({}). The content of the bash variable can be checked or modified based on the programming requirements by using variable or parameter substitution.

In this tutorial, we will learn different ways of substituting bash variables.

Declaring variables in bash

A variable is a container that is used to store a particular value temporarily. No data type declaration is mandatory to declare bash variables. A variable name may contain characters, numbers, and underscores ( _ ). The ‘$’ symbol is not used to declare or assign a bash variable but the ‘$’ symbol is used to read the content of the assigned variable.

Any string or number can be assigned in a bash variable by using the assignment operator without any space. The ‘name’ variable assignment is valid because no space was not used before and after the ‘=’ symbol. The ‘quantity’ variable assignment is invalid because the space was used before and after the '=' symbol.

The value of the ‘name’ variable (previously assigned) has been printed here by using the `echo` and `printf` commands.

At first, the value of the $nam e variable which is 'Exampledotcom', has been printed without concatenating by any string value. Next, the $name variable has been printed by concatenating it with a string value.

What is variable substitution in bash?

The way of substituting the value of a variable by using another variable or command or parameter expansion is called bash variable substitution. We have discussed different types of bash variable substitutions in this section of this tutorial.

Substitute variable by another variable or parameter

Two different ways of substituting variables with string values have been shown here.

Substitute variable by '$' symbol

You can substitute the bash variable with another variable by reading the value of the variable by using the '$' symbol. The values of two variables have been substituted with another string value into a variable in the following script.

The value of the $string1 variable is 'Bash' and the value of the $string2 variable that is ' variable' have been substituted with the string value, 'Substitution' into the $sub variable.

Substitute variable using the parameter

You can substitute bash variables by using “${parameter}”. In the following script, three variables have been initialized with three string values and substituted into another variable that has been printed later.

The value of $variable1 is 'Linux', the value of $variable2 is 'Op', and the value of $variable3 is 'Sys'. The values of these variables have been substituted into the variable, $sub.

Substitute variable by command

The command substitution is another way of substituting variables in bash. The ‘$()’ is used for applying command substitution. In this case, the variable is substituted by the output of a command. There are some differences between parameter substitution (‘${}’) and command substitution (‘$()’) which have been discussed in this section.

Difference between ‘${parameter}’ and ‘$(command)’:

Parameter SubstitutionCommand Substitution

Use of command substitution:

The username of the currently logged-in user will be substituted in the $user variable by executing the command, `whoami` and the value of this variable will be printed later.

According to the output, the currently logged-in username is 'ubuntu'.

Substitute variable by defining default shell variable

Many ways exist in bash to substitute the variable by defining the default shell variable. Three of them are ":=", ":-", and ":+". The ":=" is used to print the newly assigned value if the variable is not set before. The ":-" is used to print the previously assigned value if the variable is set before. The ":+" is used to print the newly assigned value if the variable is set before.

Here, the $OS variable was not initialized before. So, 'Ubuntu' has been printed in the first output. 'Ubuntu' has been printed in the second output because the $OS was set. 'Debian' has been printed in the third output because the $OS was set.

Array variable substitution

An array of numbers has been defined and the value of the third index of the array has been printed by array variable substitution in the following script.

The 3rd index value of the array is 34 which has been printed here.

Substitute variable in single quotes

The way of substituting a variable with another variable with the string enclosed by a single quote ( ' ) has been shown in the following script.

Here, the value of the $string variable has been substituted by adding it in the middle of two strings, ‘Variable ‘ and ‘ tutorial’.

Substitute variable using parameter expansion options

The variable can be substituted in different ways by using parameter expansion options. The use of parameter expansion to substitute the part of a variable has been shown in the following script.

The value of $string is 'Bash is a scripting language' that has been substituted into the $sub after replacing the word, 'scripting' with 'popular' by using parameter expansion.

Bash variable substitution has been explained in multiple ways in this tutorial to clear the concept of variable substitution and it will help you to substitute variables in your script on demand.

Last updated 10 months ago

example of substitute variable in single quotes

String Manipulation in Bash

Last updated: March 18, 2024

bash variable assignment substitution

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

1. Overview

Bash is a sh-compatible shell and command processor and string manipulation is one of the most common tasks to be done in a shell environment.

In this tutorial, we’ll learn how to operate on strings using Bash.

2. String Variable Declaration and Assignment

Bash doesn’t have a type system, all variables are strings. However, variables can have attributes that change or constrain their behavior that can be beneficial even when dealing with strings.

2.1. Declaration

A simple declaration and value assignment looks like this:

Mind that there are no spaces before or after the equals sign. If we want to assign attributes to a variable, we can use declare command. For example, the -r flag will make it read-only:

Now if we try to assign some other value to that variable we will get an error:

2.2. Reading

We can ask the user for input using the read command :

The -p flag allows us to specify prompt text without typing additional echo commands. The last parameter of the command is the name of a variable. If we don’t specify a name here, the default will be REPLY .

3. Pattern Matching and Substitution

3.1. length.

We can access the length of a string using the hash (#) operator inside parameter expansion before the variable name:

3.2. Substrings

We can extract a substring using the colon (:) operator inside the parameter expansion, providing the starting position of substring and optionally length of the substring :

3.2. Pattern Matching

Bash has a built-in simple pattern matching system . It consists of a few wildcards:

  • * – matches any number of characters
  • + – matches one or more characters
  • [abc] – matches only given characters

For example, we can check if the file has a .jpg extension using a conditional statement :

There’s also an extended matching system called “extended globbing”. It enables us to constraint wildcards to specific patterns:

  • *(pattern) – matches any number of occurrence of pattern
  • ?(pattern) – matches zero or one occurrence of pattern
  • +(pattern) – matches one or more occurrence of pattern
  • !(pattern) – negates the pattern, matches anything that doesn’t match the pattern

Extended globbing must be turned on with the shopt command. We can improve the last snippet to also match the .jpeg extension:

If we need more expressive pattern language we can also use regular expressions with the not-equals (=~) operator:

We can use Extended Regular Expressions here, like when calling grep with the -E flag. If we use the capture groups, they’ll be stored in the BASH_REMATCH array variable and can be accessed later.

3.3. Removing Matched Substring

Bash provides us with a mechanism to remove a substring from a given string using the parameter expansion. It always removes only one matched substring. Depending on usage, it can match the longest or shortest substring and match starting from the beginning or from the end.

It’s important to note that it doesn’t modify a variable, and only returns a modified value. To make this fact explicit, we’ll use read-only variables in examples.

So, let’s remove an extension from a filename. To do this, we need to match from the end of the string using the percent (%) operator. The singular operator will match the shortest substring, double will match the longest one:

Because we used a singular percent sign, we matched only the .js substring. If we’d like to filter out all the extensions we’d do:

We can also remove filename, leaving only extensions. In that case, we need to start from the beginning using the hash (#) operator:

Analogically to the previous example, if we would like to leave only last extension we need to use a double-hash:

3.4. Substituting Matched Substring

Instead of just removing substring we can substitute it using slash (/) operator.   The singular operator changes the first match and the double operator changes all matches. Both match the longest possible substring.

Let’s write code that changes the file name while leaving the extension intact:

4. Case Study

Let’s put features described above to good use. We will write a script that updates all old version strings (for example 1.0.1 to 1.1.0) inside a provided file and also keeps backup of old file with old version attached to its name.

We will pass filename and version strings as arguments to the script but we will redeclare them to make the rest of the code more readable. Finally, we will use the redirection mechanism to save modified content.

In this tutorial, we learned how to manipulate strings in pure Bash, without the help of external tools, from declaration to substitution.

How-To Geek

How to work with variables in bash.

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

Hannah Stryker / How-To Geek

Quick Links

What is a variable in bash, examples of bash variables, how to use bash variables in scripts, how to use command line parameters in scripts, working with special variables, environment variables, how to export variables, how to quote variables, echo is your friend, key takeaways.

  • Variables are named symbols representing strings or numeric values. They are treated as their value when used in commands and expressions.
  • Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters.
  • Variables can be used to store and reference values. The value of a variable can be changed, and it can be referenced by using the dollar sign $ before the variable name.

Variables are vital if you want to write scripts and understand what that code you're about to cut and paste from the web will do to your Linux computer. We'll get you started!

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

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

my_boost=Linux

his_boost=Spinach

this_year=2019

Defining variables in Linux.

To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

echo $my_name

echo $my_boost

echo $this_year

Using echo to display the values held in variables in a terminal window

Let's use all of our variables at once:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminal window

The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost , you just repeat what you did when you assigned its first value, like so:

my_boost=Tequila

my_boost=Tequila in a terminal window

If you re-run the previous command, you now get a different result:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminalwindow

So, you can use the same command that references the same variables and get different results if you change the values held in the variables.

We'll talk about quoting variables later. For now, here are some things to remember:

  • A variable in single quotes ' is treated as a literal string, and not as a variable.
  • Variables in quotation marks " are treated as variables.
  • To get the value held in a variable, you have to provide the dollar sign $ .
  • A variable without the dollar sign $ only provides the name of the variable.

Correct an incorrect examples of referencing variables in a terminal window

You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

drink_of-the_Year="$my_boost $this_year" in a terminal window

Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution. To illustrate the difference, here's a script that counts the files in the /dev directory.

Type this into a text file, and then save it as fcnt.sh (for "file count"):

#!/bin/bashfolder_to_count=/devfile_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

Before you can run the script, you have to make it executable, as shown below:

chmod +x fcnt.sh

chmod +x fcnt.sh in a terminal window

Type the following to run the script:

./fcnt.sh in a terminal window

This prints the number of files in the /dev directory. Here's how it works:

  • A variable called folder_to_count is defined, and it's set to hold the string "/dev."
  • Another variable, called file_count , is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ) . Note there's a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it's passed a value to hold; it isn't concerned with how the value was obtained.
  • The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to "/dev." So, the script executes the command "ls /dev."
  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the "/dev" directory. This value is assigned to the file_count variable.
  • The final line uses echo to output the result.

But this only works for the "/dev" directory. How can we make the script work with any directory? All it takes is one small change.

Many commands, such as ls and wc , take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files , you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

Our scripts can accept command line parameters. They're referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there's a $0 , as well, but that's reserved to always hold the script.)

You can reference command line parameters in a script just as you would regular variables. Let's modify our script, as shown below, and save it with the new name fcnt2.sh :

#!/bin/bashfolder_to_count=$1file_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1 .

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it's not hardcoded to work only with "/dev."

Here's how you make the script executable:

chmod +x fcnt2.sh

chmod +x fcnt2.sh in a terminal window

Now, try it with a few directories. You can do "/dev" first to make sure you get the same result as before. Type the following:

./fnct2.sh /dev

./fnct2.sh /etc

./fnct2.sh /bin

./fnct2.sh /dev in a terminal window

You get the same result (207 files) as before for the "/dev" directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

To shorten the script, you could dispense with the variable, folder_to_count , altogether, and just reference $1 throughout, as follows:

#!/bin/bash file_count=$(ls $1 wc -l) echo $file_count files in $1

We mentioned $0 , which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it's renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

The following are the other special preset variables:

  • $# : How many command line parameters were passed to the script.
  • $@ : All the command line parameters passed to the script.
  • $? : The exit status of the last process to run.
  • $$ : The Process ID (PID) of the current script.
  • $USER : The username of the user executing the script.
  • $HOSTNAME : The hostname of the computer running the script.
  • $SECONDS : The number of seconds the script has been running for.
  • $RANDOM : Returns a random number.
  • $LINENO : Returns the current line number of the script.

You want to see all of them in one script, don't you? You can! Save the following as a text file called, special.sh :

#!/bin/bashecho "There were $# command line parameters"echo "They are: $@"echo "Parameter 1 is: $1"echo "The script is called: $0"# any old process so that we can report on the exit statuspwdecho "pwd returned $?"echo "This script has Process ID $$"echo "The script was started by $USER"echo "It is running on $HOSTNAME"sleep 3echo "It has been running for $SECONDS seconds"echo "Random number: $RANDOM"echo "This is line number $LINENO of the script"

Type the following to make it executable:

chmod +x special.sh

fig13 in a terminal window

Now, you can run it with a bunch of different command line parameters, as shown below.

./special.sh alpha bravo charlie 56 2048 Thursday in a terminal window

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

To see the active environment variables in your Bash session, use this command:

env | less in a terminal window

If you scroll through the list, you might find some that would be useful to reference in your scripts.

List of environment variables in less in a terminal window

When a script runs, it's in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We'll show you how to this with two scripts.

First, save the following with the filename script_one.sh :

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./script_two.sh# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var , and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh . When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

The second script we'll use is script_two.sh . This is the script that script_one.sh calls. Type the following:

#!/bin/bash# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"# set new valuesfirst_var=charliesecond_var=delta# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

To run these scripts, you have to type the following to make them executable:

chmod +x script_one.shchmod +x script_two.sh

chmod +x script_one.sh in a terminal window

And now, type the following to launch script_one.sh :

./script_one.sh

./script_one.sh in a terminal window

This is what the output tells us:

  • script_one.sh prints the values of the variables, which are alpha and bravo.
  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.
  • script_two.sh changes them to charlie and delta.
  • script_one.sh prints the values of the variables, which are still alpha and bravo.

What happens in the second script, stays in the second script. It's like copies of the variables are sent to the second script, but they're discarded when that script exits. The original variables in the first script aren't altered by anything that happens to the copies of them in the second.

You might have noticed that when scripts reference variables, they're in quotation marks " . This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

Here's an example:

site_name=How-To Geek

site_name=How-To Geek in a terminal window

Bash sees the space before "Geek" as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing — not even the "How-To" text.

Try that again with quotation marks around the value, as shown below:

site_name="How-To Geek"

site_name="How-To Geek" in a terminal window

This time, it's recognized as a single value and assigned correctly to the site_name variable.

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what's going to happen is what you want. You can also catch any mistakes you might have made in the syntax.

Linux Commands

Files

Processes

Networking

  • Linux & macOS Terminal

Stack Exchange Network

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

Q&A for work

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

Use a variable reference "inside" another variable

I'm sure it is relatively simple, I just don't know how to do it.

I want to something like echo ${$myvar} which i want interpreted as ${$myvar} -> ${6} -> value

  • shell-script
  • variable-substitution

mirabilos's user avatar

  • 8 The technical term is variable indirection . –  Thor Commented Jun 24, 2012 at 13:18

4 Answers 4

You can do this with eval , built-in to many fine shells, including ksh:

The trick is to double-quote the string you feed to eval so that $myvar gets substituted with "6", and to backslash the outer dollar-sign, so that eval gets a string "$6".

I got "%user" for the output, but I tried it on a multi-processor RHEL machine.

SebMa's user avatar

  • 6 You are officially the Supreme Exalted Grand Master of the week b/c that even works on the unfathomably awful ksh (really pdksh) in OpenBSD 5.4. If you want to set var vv to the value of the var whose name is in the var vn , just do vv=$( eval "echo \$$vn" ) . Thanks a ton! –  execNext Commented Apr 5, 2014 at 0:07

Indirect variable reference

Modern advanced shells have a method to reference the value of a variable whose name is stored in another variable. Unfortunately the method differs between ksh, bash and zsh.

In mksh ≥R39b, you can make myvar a nameref:

This doesn't work in ATT ksh93 because it doesn't support namerefs to positional parameters. In the case where you have a variable containing a variable name, you can use this method.

In bash ≥2.0, you can write

In zsh, you can write

In older shells, including ksh88 and pdksh, your only recourse when you have a variable containing another variable name and want to use the value of this variable eval , as explained by Bruce Ediger . This solution works in any Bourne/POSIX shell.

Using an array

This is the best method here: it's simpler and more portable.

For your use case, in any shell with arrays (all ksh variants, bash ≥2.0, zsh), you can assign to an array variable and take the element you wish. Beware that ksh and bash arrays start numbering at 0, but zsh starts at 1 unless you issue setopt ksh_arrays or emulate ksh .

If you want to copy the positional parameters to an array variable a :

In ksh93, mksh ≥R39b, bash ≥2.0 and zsh, you can use the array assignment syntax:

Community's user avatar

  • Wow, your 'Bourne/POSIX' solution also works in OpenBSD 5.4's ksh/pdksh. To apply it to the example in my comment to Bruce Ediger's answer above, just do eval "vv=\${$vn}" . Merci beaucoup, kind sir. –  execNext Commented Apr 5, 2014 at 0:23
  • echo ${(P)myvar} is p a var, like p=1 ? –  Timo Commented Jun 1, 2021 at 13:05
  • 1 @Timo I guess you're asking about (P) ? It's a parameter expansion flag . –  Gilles 'SO- stop being evil' Commented Jun 1, 2021 at 13:10
  • I have code: s_cust_plugin='s|custom/plugins/'; echo "b=$0\na=${((P)s_cust_plugin$1/|)b}\necho $a[2] loaded" . Result: add_zsh_plugin:2: error in flags -- I want to echo the name of script that I invoke with exec zsh after adding this code to the script. –  Timo Commented Jun 1, 2021 at 13:15
  • 1 @Timo What you wrote is syntactically incorrect and I can't figure out what you intended to do. This is too complicated for a comment. Ask a new question. –  Gilles 'SO- stop being evil' Commented Jun 1, 2021 at 13:29

As indicated by Gilles (who provided the bash part of the answer), also not invalidating Bruce Ediger’s (on how to do it portably with eval ), here’s how to do it with nameref in recent mksh (and AT&T ksh93, except – as @Gilles commented – namerefs cannot refer to positional parameters in AT&T ksh, only to named parameters):

Added the -- after set for improved resistence, too.

  • As of ksh 93u, namerefs can't reference positional parameters ( typeset: 6: invalid variable name ). –  Gilles 'SO- stop being evil' Commented Feb 27, 2014 at 14:35

Another use of arrays

Haven't used either ksh or any variant for some time, so I'm not sure if ksh(or bash) has a similar capability. My primary shell is zsh. I use arrays when handling output from commands like iostat because they produce multiple lines, and not all lines are the same format/length.

The above also bypasses the use of positional parameters. Now, if you want to generate, say, an array of devices:

I find smaller chunks much easier to handle. You may or may not need to use indirect variable reference, depending on your code. Knowing how it works is still a good thing to know. I use it myself.

Friartek's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged shell-script ksh variable-substitution ..

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network

Hot Network Questions

  • How am I supposed to solder this tiny component with pads UNDER it?
  • How is AC and DC defined?
  • string quartet + chamber orchestra + symphonic orchestra. Why?
  • Why does constexpr prevent auto type deduction in this statement?
  • How can one win a teaching award?
  • What is a “bearded” oyster?
  • Model looks dented but geometry is correct
  • Change of variable, u = y(x)
  • How can I add cache information to InboundPathProcessor?
  • Date not working correctly
  • How to do smooth merging of two points using tikzpicture
  • What's "jam" mean in "The room reeled and he jammed his head down" (as well as the sentence itself)?
  • A continuous analogue of the notion of Hilbert basis
  • Which law(s) bans medical exams without a prescription?
  • What does St Paul mean by ' height or depth' in Romans 8:39?
  • Has the UN ever made peace between two warring parties?
  • Big bang and the horizon problem
  • Calculate transition probabilities
  • How to assign a definition locally?
  • Are There U.S. Laws or Presidential Actions That Cannot Be Overturned by Successor Presidents?
  • Email from Deutsche Bahn about a timetable change - what do I need to do?
  • Why is it surprising that the CMB is so homogeneous?
  • Can a 20A circuit mix 15A and 20A receptacles, when a 20A is intended for occassional space heater use?
  • When is due diligence enough when attempting to contact a copyright holder?

bash variable assignment substitution

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

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

Get early access and see previews of new features.

Assigning one variable to another in Bash?

I have a doubt. When i declare a value and assign to some variable, I don't know how to reassign the same value to another variable. See the code snippet below.

It should display my output as

...but instead the actual output is:

Charles Duffy's user avatar

  • I edited the title, as the question doesn't appear to have anything to do with declaring variables. (Variables can be declared in shell, but this is necessary to explicitly set types or scope metadata, rather than to assign values). –  Charles Duffy Commented Dec 18, 2014 at 23:02
  • 1 Possible duplicate of Copy values between variables in bash script –  jww Commented Mar 12, 2019 at 5:47

2 Answers 2

To assign the value associated with the variable dest to the variable source , you need simply run dest=$source .

For example, to assign the value associated with the variable arg2 to the variable a :

The use of lower-case variable names for local shell variables is by convention, not necessity -- but this has the advantage of avoiding conflicts with environment variables and builtins, both of which use all-uppercase names by convention.

sdgfsdh's user avatar

  • Thanks for the answer. You got it right. Even i thought is that this much simple. But my i am posting my script here. Help me out here.. –  Murthy Commented Dec 18, 2014 at 23:21
  • @NarayanamurthyBalasubramanian, I would hope that comparing what I'm doing against your script would be enough to make it clear: Change the line assigning ARG2 to ARG2=$a -- no extra unnecessary syntax. If this still doesn't answer your question, please clarify what you need to know. –  Charles Duffy Commented Dec 18, 2014 at 23:29
  • 1 I have changed my question and added few script lines. Help me out on this. –  Murthy Commented Dec 18, 2014 at 23:31
  • Changing your question after a correct answer is given is not kosher. You should ask a new question in this case. –  Charles Duffy Commented Dec 18, 2014 at 23:41
  • No worries. Please try to follow the guidelines at stackoverflow.com/help/mcve when constructing that question. –  Charles Duffy Commented Dec 18, 2014 at 23:54

You may also want to alias rather than copy the variable. For example, if you need mutation. Or if you want to run a function multiple times on different variables. Here's how it works

Example with arrays/dictionaries:

That is, VAR becomes effectively the same as the original variable. Instead of copying , you're adding an alias . Here's an example with functions:

Whether you should use these approaches is a question. Generally, immutable code is easier to read and to reason about (in almost any programming language). However, sometimes you really need to get stuff done in a certain way. Hope this answer helps you then.

VasiliNovikov's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged linux shell or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • A string of countries (some don't exist!)
  • Rav Moshe Feinstein's advice on doing teshuvah
  • What's "jam" mean in "The room reeled and he jammed his head down" (as well as the sentence itself)?
  • Does Tempestuous Magic allow you to avoid attacks of opportunity *after* they have already triggered?
  • Change of variable, u = y(x)
  • Is there a "hard problem of aesthetics?"
  • How to assign a definition locally?
  • Returning to the US for 2 weeks after a short stay around 6 months prior with an ESTA but a poor entry interview - worried about visiting again
  • Some of them "have no hair"
  • GeometricScene not working when too many polygons are given
  • What are some limitations of this learning method?
  • Would a material that could absorb 99.5% of light be able to protect someone from Night Vision?
  • How to achieve 24t-38t front chainrings
  • What does St Paul mean by ' height or depth' in Romans 8:39?
  • Why is Germany looking to import workers from Kenya, specifically?
  • Is it possible to monitor the current drawn by a computer from an outlet on the computer?
  • Terminated employee will not help the company locate its truck
  • CC BY-SA 2.5 License marked as denied license in the FOOSA tool after upgrading to React Native 0.74 version
  • How to react to a rejection based on a single one-line negative review?
  • Is it possible to make sand from bones ? Would it have the same properties as regular sand?
  • Hungarian Immigration wrote a code on my passport
  • Does General Relativity predict Mercury's orbital precession without other planets?
  • Can a 20A circuit mix 15A and 20A receptacles, when a 20A is intended for occassional space heater use?
  • Smallest prime q such that concatenation (p+q)"q is a prime

bash variable assignment substitution

IMAGES

  1. Bash Script

    bash variable assignment substitution

  2. Bash Variables

    bash variable assignment substitution

  3. How to use Variables in Bash

    bash variable assignment substitution

  4. Using Variable Substitution to Reference Another Variable in PHP and BASH Script

    bash variable assignment substitution

  5. How to Assign Variable in Bash

    bash variable assignment substitution

  6. Bash Script

    bash variable assignment substitution

VIDEO

  1. Working with BASH shell

  2. Intermediate Bash Scripting Tutorial: How to Pass and Reference Arguments in Functions

  3. learn bash data structure variable , array , list with vagrant and virtualbox

  4. Master brace expansion & substitution in Shell Scripting!

  5. Bash Basics -- How to Use declare and array on Linux

  6. Bash script select options

COMMENTS

  1. How To Use Bash Parameter Substitution Like A Pro

    1. Setting Up Default Shell Variables Value. The syntax is as follows: ${parameter:-defaultValue} var = ${parameter:-defaultValue} If parameter not set, use defaultValue. In this example, your shell script takes arguments supplied on the command line.

  2. Shell Parameter Expansion (Bash Reference Manual)

    3.5.3 Shell Parameter Expansion. The '$' character introduces parameter expansion, command substitution, or arithmetic expansion.The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.

  3. bash

    This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable. excerpt. ${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

  4. How to Do Bash Variable Substitution (Parameter Substitution)

    Substitute variable using the parameter. You can substitute bash variables by using "$ {parameter}". In the following script, three variables have been initialized with three string values and substituted into another variable that has been printed later. #Assign the first variable. variable1='Bash'.

  5. 13-C.7: Shell Expansion / Variable Substitution / Command Substitution

    Shell Parameter and Variable Expansion. The "$" character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.

  6. Advanced Bash Shell Scripting Guide

    Advanced Bash-Scripting Guide: Chapter 4. Introduction to Variables and Parameters. 4.1. Variable Substitution. The name of a variable is a placeholder for its value, the data it holds. Referencing its value is called variable substitution. Let us carefully distinguish between the name of a variable and its value.

  7. How to Do Bash Variable Substitution (Parameter Substitution)

    Bash variable substitution or parameter substitution is a very useful feature of bash. Generally, it is done in the bash by using the '$' character and the optional curly brackets ( {}). The content of the bash variable can be checked or modified based on the programming requirements by using variable or parameter substitution.

  8. bash

    1. @haccks $(echo var=foo) is a simple command with a single word. In step 1, we check for assignments and redirections. $(echo var=foo) is not an assignment or redirection, it's just a command substitution. Then we move on to step 2. As part of expansion, we run echo var=foo, capture its result (the string var=foo ), and substitute it.

  9. Quoting within $ (command substitution) in Bash

    You can nest command expansions as much as you like. With $() you always create a new quoting context, so you can do things like this: foo "$(bar "$(baz "$(ban "bla")")")" You do not want to try that with backticks. Share. Improve this answer. edited Apr 27, 2021 at 9:22. Stéphane Chazelas. 558k 93 1.1k 1.6k.

  10. Command Substitution: Use Output as Variable in Bash

    To use the dollar parentheses for command substitution, all you have to do is follow the given command syntax: Variable=$(command) You can also add additional text to support the command output as shown here: Variable="Optional text $(command)" Let me give you a simple example.

  11. bash

    In Bash, the line. A=${B:-C} will assign the value of the variable B to the variable A if B is set and not null. Otherwise the variable A will get the value C, i.e. the string containing the single character C.. What you might want to do: B=$( some command ) A=${B:-C}

  12. String Manipulation in Bash

    String Manipulation in Bash. 1. Overview. Bash is a sh-compatible shell and command processor and string manipulation is one of the most common tasks to be done in a shell environment. In this tutorial, we'll learn how to operate on strings using Bash. 2. String Variable Declaration and Assignment. Bash doesn't have a type system, all ...

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

  14. 4.1. Variable Substitution

    4.1. Variable Substitution. The name of a variable is a placeholder for its value, the data it holds.Referencing (retrieving) its value is called variable substitution.

  15. bash

    However, is there a way to do variable substitution without assigning it to a variable? Conceptually, something like this. $ echo ${$(xclip -o -selection clipboard)/copi/knott} bash: ${$(xclip -o -selection clipboard)/copi/knott}: bad substitution This syntax fails, because var should be a variable name, not a string.

  16. variable in bash containing command substitution

    Not having the results of e.g. variable expansions considered again for other expansions is important for correctness, it allows e.g. storing an arbitrary filename in a variable without having issues immediately when it's expanded if the filename e.g. contains a $.Consider that a filename like A $2.00 thingy might otherwise trigger expansion of the second positional parameter (or command line ...

  17. Bash variable substitution and strings

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  18. shell script

    For your use case, in any shell with arrays (all ksh variants, bash ≥2.0, zsh), you can assign to an array variable and take the element you wish. Beware that ksh and bash arrays start numbering at 0, but zsh starts at 1 unless you issue setopt ksh_arrays or emulate ksh. set -A iostat -- $(iostat) echo "${iostat[5]}"

  19. How to build a conditional assignment in bash?

    90. If you want a way to define defaults in a shell script, use code like this: : ${VAR:="default"} Yes, the line begins with ':'. I use this in shell scripts so I can override variables in ENV, or use the default. This is related because this is my most common use case for that kind of logic. ;]

  20. Assigning one variable to another in Bash?

    A=(a a a) declare -n VAR=A # "-n" stands for "name", e.g. a new name for the same variable. VAR+=(b) echo "${A[@]}" # prints "a a a b". That is, VAR becomes effectively the same as the original variable. Instead of copying, you're adding an alias. Here's an example with functions: function myFunc() {.