Introduction
Backticks and $() let you run a command inside another command and use its result. This helps automate tasks by using outputs directly.
variable=`command` # or variable=$(command)
current_date=`date`current_date=$(date)
files_count=$(ls | wc -l)
nested_example=$(echo $(date))
#!/bin/bash # Get current user name using backticks user_name=`whoami` # Get current user name using $() user_name_dollar=$(whoami) # Print both results echo "User name with backticks: $user_name" echo "User name with \$(): $user_name_dollar" # Count files in current directory file_count=$(ls | wc -l) echo "Number of files here: $file_count"
$(date) do in a bash script?$() and replaces it with the command's output.$(date)date command outputs the current date and time, so $(date) is replaced by that output.date command and replaces $(date) with its output -> Option B`command` or $(command). Both the backtick version and the incomplete $() version look valid at first.echo `ls -l` uses backticks which are valid but less readable and harder to nest. echo $(ls -l) uses $() which is modern and preferred. echo $[ls -l] uses invalid syntax with $[]. echo $(ls -l misses closing parenthesis.files=$(ls /tmp) echo "$files"
ls /tmp lists files in /tmp. Using files=$(ls /tmp) stores that output as a string with filenames separated by newlines.echo "$files" prints the content of files preserving newlines, so it lists all files and directories one per line.current_dir=`pwd echo "Current directory is: $current_dir"
pwd.file_count. Which command correctly uses command substitution to do this?ls ~ and pipe to wc -l to count lines (files).$(ls ~ | wc -l) to run the full command and store output in file_count. The other options miss the pipe or fail to use command substitution.Pass the test and this pattern moves unknown