Comparing Command Substition in Bash to Anonymous/Lambda Functions (from Lisp) in Python
The aim of this page is to explain command substitution and lambda functions based on the particular example of Bash command substitution and Python lambdas. Notes under Command Substitution chapter of Advanced Bash Scripting Book. Remembering SICP.
Bash Command Substitution ($())
- Captures the output of a command and treats it as a value.
- Used for on-the-fly/immediate manipulation of data without needing a named variable.
- Limited scope to the current shell or subshell.
- Example:
filename="report_$(date +%Y-%m-%d).txt"
Lambda Functions (Python example)
- Define anonymous functions inline.
- Passed around as arguments to be executed later.
- Focus on functionality without named storage.
- Example:
sorted_data = data.sort(key=lambda x: x.age)
f-strings as Python’s implementation of command substitution?
- f-strings for including command output within strings (more concise, be cautious about security).
import os
username = f"Current user: {os.getlogin()}" print(username)
ANKI
Question
What is Bash command substitution?
Answer
Bash command substitution captures the output of a command and treats it as a value. It’s used for on-the-fly manipulation of data without needing a named variable.
Question
What are lambda functions?
Answer
Lambda functions are anonymous functions defined inline. They are passed around as arguments to be executed later and focus on functionality without named storage.
Question
What are the key differences between bash command substitution and lambda functions?
Answer
Command substitution captures output, lambda functions define logic. Command substitution is temporary (current shell), lambdas can be passed around. Bash functions provide modularity similar to lambdas (but not anonymous).
Question
How can you capture command output in Python?
Answer
Python has two ways to capture command output:
- The
subprocess
module for executing external commands and capturing output (more flexible). - f-strings for including command output within strings (more concise, be cautious about security).