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.

Pavol Kutaj
2 min readMay 1, 2024

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:

  1. The subprocess module for executing external commands and capturing output (more flexible).
  2. f-strings for including command output within strings (more concise, be cautious about security).

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com