Linux variable in string

Using Variables with Sed in Bash

If you’ve every wanted to do some simple find and replace on string values sed is pretty straightforward way to do it from the command line or a script.

sed ‘s/findme/replacewithme/g’ file-to-search.txt > file-to-write-output.txt

In this command we define a few things:

  • String to find in the supplied file, ex: findme
  • String to replace all instances of the found string with, ex: replacewithme
  • Path to file to search, ex: file-to-search.txt
  • Path to file to output results (optional), ex: file-to-write-output.txt

This works well but it’s hard coded and not very flexible, let’s use a few variable’s to fix that. In order for our variables to be recognized and interpreted we need to use » » , double quotes around our command. And to avoid some (not all) issues with strings possibly being passed in without escaping we can change our delimiter from / to | .

OLD=find-this-string
NEW=replace-with-this-string

sed «s|$OLD|$NEW|g» file-to-search.txt

Updates to our command and portability have drastically improved with this small change. Note: we haven’t addressed all issues with escaping characters. If you control the variables for input and output, be sure to escape characters and test accordingly.

Источник

Add variable value into string

I want to add a variable value to string content quoted with ‘ ‘ because of the special characters inside. For example:

a=500 str='#Test d-i partman-auto/expert_recipe string \ boot-root :: \ $a 10000 1000000000 ext4 \ $primary < >$bootable < >\ method < format >format < >\ use_filesystem < >filesystem < ext4 >\ mountpoint < / >\ . ' 

Unfortunately, I can’t operate with the value of $a inside the ‘ ‘. It’s aways returning me $a versus its value=500

2 Answers 2

You need to leave the «inside» of the single quotes.
Close and re-open the single quotes:

a=500 primary=one bootable=two str='#Test d-i partman-auto/expert_recipe string \ boot-root :: \ '"$a"' 10000 1000000000 ext4 \ '"$primary"' < >'"$bootable"' < >\ method < format >format < >\ use_filesystem < >filesystem < ext4 >\ mountpoint < / >\ . ' echo "$str" 

+1. In other words, the key point is that despite the OP’s expectation, this isn’t actually a «string». In Bash, ‘. ‘ and «. » are just notations for disabling certain special meanings within a specified stretch of source text, analogously to how \ disables a special meaning in the following source character. ‘foo’ , «foo» , and ‘f’o»o» all just mean foo .

Interpolate all $ variables (using » ) — and escape any dollar signs that you want to retain:

EXPAND_THIS=100 echo " $EXPAND_THIS \$DONT_EXPAND_THIS " 

Or interpolate no $ variables (using ‘ ) — and start a new, interpolated, string whenever you do want to interpolate a variable:

echo ' '$EXPAND_THIS' $DONT_EXPAND_THIS ' 

Surrounding in quotes the variables that you want interpolated, may provide safety in some situation (though I can’t currently think of an example):

echo 'blah blah '"$EXPAND_THIS"' $DONT_EXPAND_THIS ' 

Источник

Читайте также:  Linux check cuda version

Bash Variable in String

Bash Variable in String

Variable is one of the most widely used, or in other words, we say it to be the most essential feature of programming where it provides an ability to the programmer to reference a name or a label to some other quantity. As the name suggests, the variable is something that can vary. For example, in our mathematics, we assume x as 10. Here it is important to know that during manipulation of the equation in mathematics the value which x is storing might change, but the value 10 will always be value 10. Similarly, in computers, we use a variable so that it can be assigned some value and can either be referenced to print or access for manipulation. In this topic, we are going to learn about Bash Variable in String.

Web development, programming languages, Software testing & others

In the programming world, the variable is thought to be an advanced programming concept, where the programmer would use variable only when the value is not known to the code from the start. For example, if we write a program to calculate the sum of 10 & 20. We know that the values can only be 10 and 20 and nothing else! We would never use variables. But in case, we don’t know what to add, we would take the help of the concept of variables, and give the flexibility to the user to enter the numbers to be added. We assume the variable to be glass which will be used when we fill water to it, or in programming words used only when the program is executed!

Now the next question we would like to answer is, how do we set a variable or in other words what’s the syntax for setting up a variable. One picky thing about bash is its “allergy” to whitespaces. In most of the programming languages, whitespaces are “cool” to use but not for the bash.

What is correct?

What is not correct?

Now, when we have allotted a value to a variable, how do we reference it? For this, a special character is employed and that’s $. Any variable that follows a dollar sign is attempted to be replaced with the value of the variable stores. This technique is known as variable expansion. In case it is not able to reference the variable it will throw out an error. We will discuss a small deviation in the next section, but first, let us look at what’s correct and what’s wrong?

What is correct?

What is not correct?

echo Var_1 [This will just print the variable name i.e. Var_1]

echo $Var_2 [Var_2 is not declared initially, would throw an error]

Failure to reference will occur in 2 cases, but not necessarily throw an error:

  1. If the dollar sign doesn’t precede the variable name (Shown in the example, we discussed above)
  2. If the dollar preceding the variable name is enclosed within single quotes. For example, echo ‘Var_1’. In this case, it will just print out the variable name (Var_1) and not its value
Читайте также:  Linux sudo сменить пользователя

Now coming to some important features of string:

Concatenating Strings

In case one needs to store a string, which is likely to be copy-pasted with every other value, one can store it in a variable and concatenate it with the values. For example, if one needs to add https://www. before every website name and end it with .com can take the help of the variable and concatenate it to the value of the website name.

Var_start="https.//www." Var_end=".com" echo $Var_start$1$Var_end

The echo statement will print out the value stored in Var_start followed by the input entered by the user ($1) and finally end with the value stored in Var_end.

Allowed Variable Names

All variable names can contain the sequence of alphanumeric characters, but the ones created by the user should start only with either alphabets or an underscore.

What is correct?

What is not correct?

Command Substitution

Bash allows standard output to be encapsulated and then expanded when executed in the shell. For example, the seq command will print the sequence of numbers given as an argument.

Arithmetic expansion

For bash one needs to perform calculations inside $(( )). In cases of advanced mathematical utilities, we use the command bc which helps in evaluating an expression. We would see some utility of the same in our examples.

Example of Bash Variable in String

Now its time for us to look into the above theoretical concepts in the real-time using example.

In the code below we will try to cover all the utilities we talked about above in a single code, obviously separated by some headings.

echo "***Assigning a variable***" Var_1="EduCBA" echo "***Printing Var_1 which is assigned value of EduCBA***" echo $Var_1 echo "***Printing Var_2 which is not assigned***" echo "***Nothing gets printed!***" Var_start="https://www." Var_end=".com" echo $Var_start$1$Var_end echo "***Sequence keyword will print 1 to 4 in different lines***" seq 1 4 echo "***The following command will print it in single line***" echo $(seq 1 4) echo "***Arthmetical operator to add 2 numbers entered by users: $2 and $3" echo $(($2+$3)) echo "***Using bc utility to restrict the number of decimals***" echo "7.5 / 2.1" | bc echo "***Using bc utility to not restrict the number of decimals***" echo "7.5 / 2.1" | bc -l

bash variable in string output

Conclusion – Bash Variable in String

In an ending note, we would encourage you to explore more on the hidden treasure of strings in bash. The capability and flexibility of bash variables in strings provide enables us to achieve any complex program within bash itself. Even using some sed and awk commands and usage of variables, one can easily achieve complex computation of data analytics as well!

We hope that this EDUCBA information on “Bash Variable in String” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Читайте также:  Linux ssh new user

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

How to use an environment variable inside a quoted string in Bash

But I can’t get the syntax to correctly expand the COLUMNS environment variable. I’ve tried various forms of the following:

svn diff $@ --diff-cmd /usr/bin/diff -x '-y -w -p -W $COLUMNS' 
svn diff $@ --diff-cmd /usr/bin/diff -x '-y -w -p -W $' 
eval svn diff $@ --diff-cmd /usr/bin/diff -x "-y -w -p -W $COLUMNS" 

BTW, using $@ unquoted makes it exactly the same as $* — which is to say that it breaks «foo bar» into two separate arguments, foo and bar . If you want to preserve the original argument list just as it was given to you, you want «$@» .

6 Answers 6

Just a quick note/summary for any who came here via Google looking for the answer to the general question asked in the title (as I was). Any of the following should work for getting access to shell variables inside quotes:

Use of single quotes is the main issue. According to the Bash Reference Manual:

Enclosing characters in single quotes ( ‘ ) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. [. ] Enclosing characters in double quotes ( » ) preserves the literal value of all characters within the quotes, with the exception of $ , ` , \ , and, when history expansion is enabled, ! . The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $ , ` , » , \ , or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed. The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

In the specific case asked in the question, $COLUMNS is a special variable which has nonstandard properties (see lhunath’s answer above).

Источник

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