FUNDAMENTALS A Complete Guide for Beginners
![icon linux](https://linuxsimply.com/wp-content/uploads/2024/05/Linux-Mascot.png)
Built-in variables undeniably play an integral part in the field of interactive Bash scripting. These variables provide critical information about the shell’s configuration and behavior which is enough to call them powerful tools in Bash. By leveraging the variables, a user can write more robust and efficient Bash scripts. So, let’s go through the article to get more ideas about the Bash built-in variables with several cases and examples.
Key Takeaways
- Learning about various built-in variables in Bash.
- Utilizing Bash built-in variables for multiple cases.
Free Downloads
What Are Built-in Variables in Bash?
Built-in variables refer to the predefined and default variable types that Bash uses to store various information. These variables provide crucial data for customizing and controlling the behavior of the Bash. Without arranging any additional setup, you can easily access these built-in variables and make scripting decisions quickly.
Some Commonly Used Built-in Variables in Bash
There are various built-in variables in Bash having different meanings based on different contexts. Here are some commonly used built-in variables lists in Bash:
Syntax | Description |
---|---|
$BASH | The path to the Bash. |
$BASH_VERSION | The version number of the Bash shell. |
$HOME | The home directory of the current user. |
$PWD | The present working directory of the current user. |
$OLDPWD | The previous working directory of the current user. |
$SHELL | The path to the default shell. |
$USER | The username of the current user. |
$UID | The user ID number of the current user. |
$HOSTNAME | The current host system name. |
$HOSTTYPE | The current host system type. |
$LINENO | Holds the current line number. |
$IFS | Splits input into separate words. |
$$ | The process ID of the current shell. |
$0 | The name of the executing script. |
$# | The number of positional parameters passed to the script. |
$@ | All positional parameters as separate strings. |
$* | All positional parameters as a single string. |
$? | The exit status of the last executed command. |
2 Cases for Built-in Variables in Bash
Built-in variables are so flexible that you can simply append them to a conditional statement or modify the value. In the following section, I’m going to share two such cases of Bash built-in variables:
Case 1: Bash Built-in Variables in Case of Conditional Statements
You can use Bash built-in variables in a conditional statement to create a directory by following the steps below:
➊ Open your Ubuntu Terminal.
➋ To open a script in the nano text editor, write the command below:
nano conditional.sh
- nano: A text editor.
- conditional.sh: This is a script. Here, I have named the script by ‘conditional.sh’. You can name any of your choices.
➌ Hereafter, write the following script inside the editor:
Script (conditional.sh) >
#!/bin/bash
#Attempting to create a directory
mkdir var_dir
if [ $? -eq 0 ]; then
echo "Directory created."
else
echo "Failed to create directory."
fi
Here, in #!/bin/bash, ‘#!’ is called ‘Shebang’ or ‘Hashbang’. ‘mkdir var_dir’ attempts to create the directory ‘var_dir’. Now, in ‘if [ $? -eq 0 ];’ then, the ‘$?’ holds the exit status of the last executed command ‘mkdir’. Then, if the exit status is 0, it indicates success, and the echo command will print “Directory created.”. If the exit status is non-zero, it indicates failure, and in the else block, the echo command will print “Failed to create directory.”.
➍ Then, press CTRL+S to save the file & press CTRL+X to exit.
➎ After that, use the command below to make the script executable:
chmod u+x conditional.sh
- chmod: Changes the permission of the files and directories.
- u+x: Adds the executable permission for the user.
- conditional.sh: The file which you want to make executable.
➏ Finally, run the script by the following command:
./conditional.sh
From the above image, you can see that I have created a new directory.
Case 2: Bash Built-in Variables in Case of Modification Purpose
You can easily modify the built-in variable “$IFS” in Bash, and alter the word-splitting behavior.
Script (modify.sh) >
#!/bin/bash
#Saving the current values of IFS
main_ifs="$IFS"
#Customizing the IFS to use commas as the delimiter
IFS=","
#Creating a string separated with comma
painting="canvas,color,brush"
#Splitting the string into an array using the modified IFS
read -ra elements <<< "$painting"
#Displaying the array elements
echo "First element: ${elements[0]}"
echo "Second element: ${elements[1]}"
echo "Third element: ${elements[2]}"
#Restoring the main IFS
IFS="$main_ifs"
Here, I have saved the actual value of ‘$IFS’ in the ‘main_ifs’, and modified ‘$IFS’ to use a comma (,) as the delimiter. Next, in the line ‘painting=”canvas,color,brush”‘, I have created a string called ’painting’ which is separated by commas. Hereafter, in ‘read -ra elements <<< “$painting”‘, I have used the modified ‘$IFS’ to split the string into an array called ‘elements’. Finally, the echo commands display the elements of the array and the actual value of ‘$IFS’ is stored to prevent unexpected behavior of the script.
Now, run the following script by the command below:
./modify.sh
The above snapshot displays the array elements done by modifying the variable ‘$IFS’.
3 Examples of Bash Built-in Variables for Script Control
Certainly, Bash built-in variables are very useful for script control purposes. Let’s go through some script control examples of built-in variables in Bash:
Example 1: Using Built-in Variables in Bash for Checking Command Status
By using the built-in variable ‘$?’, you can easily check the command status in a Bash script. Though sometimes it doesn’t work visibly in the code, it performs its task implicitly in the conditional statements.
Script (command-status.sh) >
#!/bin/bash
# Checking a file’s existence
file="new.txt"
if [ -f "$file" ]; then
echo "File '$file' exists."
else
echo "File '$file' does not exist."
fi
Here, in ‘if [ -f “$file” ]; then’, the ‘-f’ test operator checks if ‘new.txt’ exists in the ‘$file’ variable. The ‘[ ]’ command evaluates the return values of the condition. If the condition is true, then the echo command prints “File ‘$file’ exists.”. Or if the condition is false, then the echo command prints “File ‘$file’ does not exist.”.
The ‘$?’ variable is not apparently used in the code. But it contributes by holding the exit status or return values of the ‘[ ]’ command.
Now, run the script by the following command:
./command-status.sh
From the image, you can see that the mentioned file does not exist.
Example 2: Using Built-in Variables in Bash for Checking the Number of Arguments
You can use the built-in variable ‘$#’ to define the number of arguments passed to a script and handle various cases under the conditional statements.
Script (argument.sh) >
#!/bin/bash
#Checking how many arguments are there
if [ $# -eq 0 ]; then
echo "No arguments provided."
elif [ $# -eq 1 ]; then
echo "One argument provided: $1"
else
echo "Multiple arguments provided: $@"
fi
Here, the special variable ‘$#’ inside the if condition contains the number of arguments (excluding the script name). First, the line ‘if [ $# -eq 0 ]; then’ checks if the number of arguments is equal to 0. If there are no arguments, the condition becomes true, and the echo command prints “No arguments provided.”
When any arguments are passed to the script, the first condition becomes false, and the line ‘elif [ $# -eq 1 ]; then’ checks if the number of arguments is equal to 1. If there is one argument, then the script executes the line echo “One argument provided: $1” where the first argument is stored in ‘$1’.
If all the previous conditions are false, the script proceeds to the else block. When there is more than one argument passed to the script, the echo command prints “Multiple arguments provided: $@”. Here, the special variable ‘$@’ resembles all the parameters as separated by spaces.
Now, run the following script by the command below:
Scenario 1 >
./argument.sh
In scenario 1, you can see that I have used no arguments while running the script ‘argument.sh’. So, the output tells that no arguments are provided.
Scenario 2 >
./argument.sh hello
In scenario 2, I have run the script with an argument ‘hello’. That’s why the output shows the one argument that is provided during the script execution.
Scenario 3 >
./argument.sh hello Bash
In scenario 3, I have run the script with two arguments ‘hello’, and ‘Bash’. So, the output displays the multiple arguments provided with the script execution.
Example 3: Using Built-in Variables in Bash for Debugging
You can use the ‘$LINENO’ variable for debugging and finding the line number of the executed commands. This will help you to troubleshoot the errors of a Bash script.
Script (variable-debug.sh) >
#!/bin/bash
#Debugging
function debug_func() {
echo "debug_func is being executed at line number: $LINENO"
}
echo "This is line number: $LINENO"
debug_func
echo "This is line number: $LINENO"
echo "Error occurs here.."
echo "This is line number: $LINENO"
# More code..
echo "End of the script at line number: $LINENO"
The line ‘function debug_func() {‘ defines the function named ‘debug_func’ and the echo command inside the function prints the current line number where the function is executed by using the ‘$LINENO’ variable. Then, the line echo “This is line number: $LINENO” prints the current line number where the echo command is executed.
Now, the line ‘debug_func’ indicates the predefined function call. Then, it executes the echo command that prints the line number where the echo command is executed in the function. After that, the line echo “This is line number: $LINENO” prints the current line number after the debug_func function calling.
Hereafter, the line echo “Error occurs here..” dictates that some errors might occur at this moment. And the line echo “This is line number: $LINENO” again prints the current line number here. Next, you can add more code in the ‘# More code..’ section. Finally, echo “End of the script at line number: $LINENO” prints the current line number at the end of the script.
Now, run the following script by the command below:
./variable-debug.sh
The above image demonstrates how the ‘$LINENO’ variable helps to debug by keeping track of command executions and unexpected errors.
Conclusion
Throughout the article, I have outlined how one can execute Bash built-in variables practically and how these variables can help you to control the shell’s environment. However, to wrap up, use these readily available variables in an explicit way for illustrating adaptable and user-friendly scripts.
People Also Ask
Related Articles
- An Ultimate Guide of Using Bash Environment Variables
- The “.bashrc” Environment Variables [4 Cases]
- String Variables in Bash [Manipulation, Interpolation & Testing]
- What is Variable Array in Bash? [4 Cases]
- An Extensive Exploration of Bash Special Variables [9 Examples]
- What is Boolean Variable in Bash? [3 Cases With Examples]
- What is HereDoc Variable in Bash? [5 Practical Cases]
- What is PS1 Variable in Bash? [3 Customization Examples]
- What is PS3 Variable in Bash? [3 Practical Examples]
<< Go Back to Types of Variables in Bash | Bash Variables | Bash Scripting Tutorial