Skip to content

What is the Difference Between ${} and $() in Bash?

Advertisement

Bash, which stands for Bourne-Again SHell, is a popular Unix shell used for scripting. If you work with Bash scripts, it’s important to understand different syntax elements to make your scripts efficient and error-free.

In this article, we’ll explain the differences between the ${} and $() syntax in Bash and show you how to use them.

The ${} Syntax: Parameter Expansion

The ${} syntax in Bash is used for parameter expansion. This means it helps you get and change the value of a variable. The syntax uses a dollar sign ($) followed by curly braces ({}) containing the variable name or an expression. You can do several things with parameter expansion, like extracting part of a string, changing case, and more.

Examples of ${} usage:

  1. Simple variable expansion:
    
    name="Rahul Kumar"
    echo ${name}
    
    
  2. Substring extraction (getting part of a string):
    
    name="Tecadmin.net"
    echo ${name:0:4}
    
    
  3. Default value assignment (using a default value if the variable is empty):
    
    default_name="Tecadmin"
    name=""
    echo ${name:-$default_name}
    
    

The $() Syntax: Command Substitution

The $() syntax in Bash is used for command substitution. This means you can run a command and use its output in your script. This is useful when you want to use the result of a command as an argument for another command or store it in a variable.

Examples of $() usage:

  1. Basic command substitution:
    
    date=$(date)
    echo "Today's date is $date"
    
    
  2. Using command substitution in a loop:
    
    for file in $(ls)
    do
      echo "Processing file: $file"
    done
    
    

Comparing ${} and $()

Here are the key differences between ${} and $():

  • Purpose: ${} is used for parameter expansion to manipulate and get the value of a variable. $() is used for command substitution to run a command and use its output.
  • Syntax: ${} uses curly braces ({}) around the variable name or expression. $() uses parentheses (()) around the command you want to run.
  • Usage: Use ${} when you need to work with variables, like extracting part of a string or setting default values. Use $() when you need to run a command and use its output in your script.

Conclusion

Every user must know the differences between ${} and $() in Bash is important for writing good scripts. The key point is ${} is for working with variables, and $() is for running commands and using their output. Keep these differences in mind to make your Bash scripts efficient and accurate.

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

Leave a Reply

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


Back to top