How to use the command 'bb' (with examples)
The command ‘bb’ is a native Clojure interpreter for scripting. It provides a convenient way to evaluate Clojure expressions and run Clojure scripts from the command line. This article will illustrate various use cases of the ‘bb’ command along with examples and explanations for each use case.
Use case 1: Evaluate an expression
Code:
bb -e "(+ 1 2 3)"
Motivation: This use case is useful when you want to quickly evaluate a Clojure expression without the need to create a separate script file.
Explanation:
- The ‘-e’ argument is used to indicate that we want to evaluate an expression.
- The expression “(+ 1 2 3)” calculates the sum of the numbers 1, 2, and 3.
Example output:
6
Use case 2: Evaluate a script file
Code:
bb -f path/to/script.clj
Motivation: This use case allows you to run Clojure scripts stored in a file without the need to manually load and execute them in the Clojure REPL.
Explanation:
- The ‘-f’ argument is used to specify the path to the script file that you want to evaluate.
Example output:
Output produced by the script
Use case 3: Bind input to a sequence of lines from stdin
Code:
printf "first\nsecond" | bb -i "(map clojure.string/capitalize *input*)"
Motivation: This use case is useful when you want to process a sequence of lines from the standard input (stdin) using Clojure functions.
Explanation:
- The ‘-i’ argument is used to indicate that we want to bind the input to a sequence of lines from stdin.
- The expression “(map clojure.string/capitalize input)” maps the ‘clojure.string/capitalize’ function over each line of the input sequence.
Example output:
("First" "Second")
Use case 4: Bind input to a sequence of EDN values from stdin
Code:
echo "{:key 'val}" | bb -I "(:key (first *input*))"
Motivation: This use case is useful when you want to process a sequence of EDN (Extensible Data Notation) values from the standard input (stdin) using Clojure functions.
Explanation:
- The ‘-I’ argument is used to indicate that we want to bind the input to a sequence of EDN values from stdin.
- The expression “(:key (first input))” retrieves the value of the ‘key’ key from the first EDN value in the input sequence.
Example output:
'val'
Conclusion:
In this article, we have explored different use cases of the ‘bb’ command. We have seen how to evaluate Clojure expressions, run Clojure scripts, process lines from stdin, and process EDN values from stdin. The ‘bb’ command provides a versatile way to work with Clojure code from the command line, making it a powerful tool for scripting and automation.