variables

All posts tagged variables by Linux Bash
  • Posted on

    Working with Environment Variables in Bash

    Environment variables in Bash are variables that define the environment in which processes run. They store system-wide values like system paths, configuration settings, and user-specific data, and can be accessed or modified within a Bash session.

    Environment variables are essential for: - Configuring system settings. - Customizing the behavior of scripts and programs. - Storing configuration values for users and applications.

    Here’s an overview of how to work with environment variables in Bash.


    1. Viewing Environment Variables

    To see all the current environment variables, use the env or printenv command:

    env
    

    or

    printenv
    

    This will print a list of all environment variables and their values.

    To view a specific variable:

    echo $VARIABLE_NAME
    

    Example:

    echo $HOME
    

    This will display the path to the home directory of the current user.


    2. Setting Environment Variables

    To set an environment variable, you can use the export command. This makes the variable available to any child processes or scripts launched from the current session.

    Syntax:

    export VARIABLE_NAME="value"
    

    Example:

    export MY_VAR="Hello, World!"
    

    Now, the MY_VAR variable is available to the current session and any child processes.

    To check its value:

    echo $MY_VAR
    

    3. Unsetting Environment Variables

    If you no longer need an environment variable, you can remove it with the unset command.

    Syntax:

    unset VARIABLE_NAME
    

    Example:

    unset MY_VAR
    

    After running this command, MY_VAR will no longer be available in the session.


    4. Temporary vs. Permanent Environment Variables

    Temporary Environment Variables:

    Environment variables set using export are only valid for the duration of the current shell session. Once the session ends, the variable will be lost.

    Permanent Environment Variables:

    To set an environment variable permanently (so that it persists across sessions), you need to add it to one of the shell initialization files, such as: - ~/.bashrc for user-specific variables in interactive non-login shells. - ~/.bash_profile or ~/.profile for login shells.

    Example: Setting a permanent variable

    1. Open the file for editing (e.g., ~/.bashrc):

      nano ~/.bashrc
      
    2. Add the export command at the end of the file:

      export MY_VAR="Permanent Value"
      
    3. Save the file and reload it:

      source ~/.bashrc
      

    Now, MY_VAR will be available every time a new shell is started.


    5. Common Environment Variables

    Here are some common environment variables you’ll encounter:

    • $HOME: The home directory of the current user.
    • $USER: The username of the current user.
    • $PATH: A colon-separated list of directories where executable files are located.
    • $PWD: The current working directory.
    • $SHELL: The path to the current shell.
    • $EDITOR: The default text editor (e.g., nano, vim).

    Example:

    echo $PATH
    

    This will print the directories that are included in your executable search path.


    6. Using Environment Variables in Scripts

    Environment variables can be used within Bash scripts to customize behavior or store settings.

    Example Script:

    #!/bin/bash
    
    # Use an environment variable in the script
    echo "Hello, $USER! Your home directory is $HOME"
    

    You can also pass variables into scripts when you run them:

    MY_VAR="Some Value" ./myscript.sh
    

    Inside myscript.sh, you can access $MY_VAR as if it were set in the environment.


    7. Modifying $PATH

    The $PATH variable is a crucial environment variable that defines the directories the shell searches for executable files. If you install new software or custom scripts, you may want to add their location to $PATH.

    Example: Adding a directory to $PATH

    export PATH=$PATH:/path/to/my/custom/bin
    

    This command appends /path/to/my/custom/bin to the existing $PATH.

    To make this change permanent, add the export command to your ~/.bashrc or ~/.bash_profile.


    8. Environment Variables in Subshells

    When you open a new subshell (e.g., by running a script or launching another terminal), the environment variables are inherited from the parent shell. However, changes to environment variables in a subshell will not affect the parent shell.

    For example:

    export MY_VAR="New Value"
    bash  # Open a new subshell
    echo $MY_VAR  # This will show "New Value" in the subshell
    exit
    echo $MY_VAR  # The parent shell's $MY_VAR is unaffected
    

    9. Example of Using Multiple Environment Variables in a Script

    #!/bin/bash
    
    # Setting multiple environment variables
    export DB_USER="admin"
    export DB_PASSWORD="secret"
    
    # Using the variables
    echo "Connecting to the database with user $DB_USER..."
    # Here, you would use these variables in a real script to connect to a database, for example.
    

    Conclusion

    Working with environment variables in Bash is a key part of managing system configuration and making your scripts flexible and portable. By using commands like export, echo, and unset, you can configure, view, and manage variables both temporarily and permanently. Mastering environment variables will help you manage your Linux environment more effectively, automate tasks, and write more dynamic Bash scripts.

  • Posted on

    If you’ve ever used a Linux operating system used on most Virtual Private Servers, you may have heard of bash. It’s a Unix shell that reads and executes various commands.

    What Is Bash?

    Bash, short for Bourne-Again Shell, is a Unix shell and a command language interpreter. It reads shell commands and interacts with the operating system to execute them.

    Why Use Bash Scripts?

    Bash scripts can help with your workflow as they compile many lengthy commands into a single executable script file. For example, if you have multiple commands that you have to run at a specific time interval, you can compile a bash script instead of typing out the commands manually one by one. You then execute the script directly, when it’s necessary.

    Pro Tip Linux has a bash shell command manual. Type man command to find descriptions of all the technical terms and input parameters.

    Get Familiar With Bash Commands

    Bash is available on almost all types of Unix-based operating systems and doesn’t require a separate installation. You will need a Linux command prompt, also known as the Linux terminal. On Windows you would use something like PuTTy. It’s a program that contains the shell and lets you execute bash scripts. 

    1. Comments

    Comments feature a description on certain lines of your script. The terminal doesn’t parse comments during execution, so they won’t affect the output.

    There are two ways to add comments to a script. The first method is by typing # at the beginning of a single-line comment. # Command below prints a Hello World text echo “Hello, world!”

    2. Variables

    Variables are symbols that represent a character, strings of characters, or numbers. You only need to type the variable name in a command line to use the defined strings or numbers.

    To assign a variable, type the variable name and the string value like here: testvar=“This is a test variable”

    In this case, testvar is the variable name and This is a test variable is the string value. When assigning a variable, we recommend using a variable name that’s easy to remember and represents its value.

    To read the variable value in the command line, use the $ symbol before the variable name. Take a look at the example below:

    testvar=“This is a test variable”
    echo $testvar
    

    In order to let the user enter the variable contents use:

    read testvar
    echo $testvar
    

    3. Functions

    A function compiles a set of commands into a group. If you need to execute the command again, simply write the function instead of the whole set of commands.

    There are several ways of writing functions. The first way is by starting with the function name and following it with parentheses and brackets:

    function_name () {
        first command
        second command
    }
    

    Or, if you want to write it in a single line: function_name () { first command; second command; }

    4. Loops

    Loop bash commands are useful if you want to execute commands multiple times. There are three types of them you can run in bash – for, while, and until. The for loop runs the command for a list of items:

    for item in [list]
    do
        commands
    done
    

    The following example uses a for loop to print all the days of the week:

    for days in Monday Tuesday Wednesday Thursday Friday Saturday Sunday
    do
        echo “Day: $days”
    done
    

    On line 2, “days” automatically becomes a variable, with the values being the day names that follow. Then, in the echo command, we use the $ symbol to call the variable values.

    The output of that script will be as follows:

    Day: Monday
    Day: Tuesday
    Day: Wednesday
    Day: Thursday
    Day: Friday
    Day: Saturday
    Day: Sunday
    

    Notice that even with just one command line in the loop script, it prints out seven echo outputs.

    The next type of loop is while. The script will evaluate a condition. If the condition is true, it will keep executing the commands until the output no longer meets the defined condition.

    while [condition]
        do
    commands
    done
    

    5. Conditional Statements

    Many programming languages, including bash, use conditional statements like if, then, and else for decision-making. They execute commands and print out outputs depending on the conditions. The if statement is followed by a conditional expression. After that, it’s followed by then and the command to define the output of the condition. The script will execute the command if the condition expressed in the if statement is true.

    However, if you want to execute a different command if the condition is false, add an else statement to the script and follow it with the command.

    Let’s take a look at simple if, then, and else statements. Before the statement, we will include a variable so the user can input a value:

    echo “Enter a number”
    read num
    if [[$num -gt 10]]
    then
    echo “The number is greater than 10”
    else
    echo “The number is not greater than 10”
    

    OK, so that's it. The 5 building blocks of Bash in plain English. Simple, right?!