Assign a Command's Output to a Variable in Shell Script
Suppose we want to store a command output to a variable in a serval way.
- we can use back tick `
VARIABLE_NAME=`command_here`
- we can use the brackets (recommend way)
VARIABLE_NAME=$(command_here)
Example:
#!/bin/bash
CURRENT_WORKING_DIR=$(pwd)
VARIABLE_SECOND_METHOD=`pwd`
echo "${CURRENT_WORKING_DIR}"
echo "${VARIABLE_SECOND_METHOD}"
date_time=$(date +"%D-%T")
echo "${date_time}"
output:
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./assing-command-output-to-variable.sh
/home/kali/shellscript-youtube
/home/kali/shellscript-youtube
07/13/22-07:58:50