Bash Scripting – How to Initialize a String
Strings are quite crucial aspects of programming and scripting. We need to store the characters in some variables. In this article, we’ll see how to initialize strings in BASH.
Basic String Initialization
To initialize a string, you directly start with the name of the variable followed by the assignment operator(=) and the actual value of the string enclosed in single or double quotes.
#!/bin/usr/env bash a="Hello" echo $a
This simple example initializes a string and prints the value using the “$” operator. The “#!/bin/usr/env bash” is the shebang, which makes the kernel realize which interpreter to be run when executing, in our case, it’s the BASH interpreter. We have assigned the string “a” a value of “Hello”. Also, it must be noted that there should not be any whitespace around the assignment operator otherwise it generates errors in the script.
Usage of Double and single Quotes in Strings
The double quotes or single quotes might not be significant but when it comes to using variables inside the string, we make use of double quotes to expand the value of the variable.
#!/bin/usr/env bash name='Kevin' greet="Welcome $name, to GeeksforGeeks!" echo $greet
In the above example, if we don’t use double quotes in the “greet” string, the value of the variable “name” would not expand and the string will be displayed as it is.
As we can see the variable “name” is not expanded to the value and it is displayed as it is when we use single quotes when we have initialized the string “greet“.
Please Login to comment...