Assign a Command's Output to a Variable in Shell Script

In Shell scripting, assigning the output of a command to a variable is a common task. You can do this using different methods depending on the syntax you prefer.


Methods to Assign Command Output

1. Using Backticks ( )

Backticks enclose the command whose output you want to capture. However, this method is outdated and less preferred in modern scripting.

VARIABLE_NAME=`command_here`

2. Using Brackets (Recommended Method)

Brackets offer a more modern and readable way to capture command output. It also supports nesting without confusion.

VARIABLE_NAME=$(command_here)

Examples

Example 1: Capture Current Directory

#!/bin/bash
# Capturing the current working directory
CURRENT_WORKING_DIR=$(pwd)
VARIABLE_SECOND_METHOD=`pwd`

echo "Using brackets: ${CURRENT_WORKING_DIR}"
echo "Using backticks: ${VARIABLE_SECOND_METHOD}"

Output:

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./assign-command-output.sh
Using brackets: /home/kali/shellscript-youtube
Using backticks: /home/kali/shellscript-youtube

Example 2: Capture Date and Time

#!/bin/bash
# Capturing the current date and time
DATE_TIME=$(date +"%D %T")
echo "Current Date and Time: ${DATE_TIME}"

Output:

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./assign-command-output.sh
Current Date and Time: 10/17/23 08:45:00

Real-life Use Cases

Use Case 1: Disk Usage Check

#!/bin/bash
# Capture disk usage percentage for root directory
DISK_USAGE=$(df -h / | grep '/' | awk '{print $5}')
echo "Disk Usage for /: ${DISK_USAGE}"

Output:

Disk Usage for /: 28%

Use Case 2: Count Files in Directory

#!/bin/bash
# Count the number of files in the current directory
FILE_COUNT=$(ls -1 | wc -l)
echo "Number of Files in Current Directory: ${FILE_COUNT}"

Output:

Number of Files in Current Directory: 15

Use Case 3: Fetch Logged-in User

#!/bin/bash
# Get the current logged-in user
USER_NAME=$(whoami)
echo "Logged-in User: ${USER_NAME}"

Output:

Logged-in User: gaurav

Why Prefer Brackets Over Backticks?

  1. Readability: Brackets are visually clearer and easier to understand.
  2. Nesting Support: Brackets allow nested commands without ambiguity.
  3. Modern Syntax: Encouraged in modern scripting for consistency and maintainability.

Best Practices

  • Use descriptive variable names: Makes scripts easier to understand.
  • Always quote variables: Prevents issues with spaces or special characters in outputs.
  • Avoid backticks: Stick to $(...) for better readability and less error-prone code.
  • Test thoroughly: Run scripts in various environments to ensure compatibility.

Demo Video

Click Here for Demo Video

Stay tuned for more tutorials, and visit Learning Ocean for in-depth content. Happy scripting!