In Bash, you can set the output of a command as the value of a variable by enclosing the command within
$() or backticks
# Using $() result=$(date) echo $result # Using backticks result=`date` echo $result
In the above example, the
date command returns the current date and time. The output of this command is then captured in the
result variable using
$() or backticks. Finally, the value of the
result variable is printed to the console using the
You can use this method to assign the output of various command-line programs to a variable to store, manipulate or use in other parts of your Bash script.
Related Bash Tutorials
- Dynamic variable names in Bash
- How to parse command line arguments in Bash?
- Bash and shell script variable capitalization?
- How to get the directory where a Bash script is located from within the script itself?
- Parsing JSON with Unix tools
- Command not found error in Bash variable assignment
- How to run Bash commands in Python?
- Extract filename and extension in Bash?
- Looping through the content of a file in Bash