save a command's output in a variable
Keep what a command prints in a variable, or each line in an array, to use later in a script.
Steps
-
today=$(date +%F)the output of date in today
-
count=$(ls | wc -l)a count
-
echo "$today"use it; the quotes keep spaces and lines as they are
-
mapfile -t lines < <(git branch)each line of the output in an array (bash 4)
-
if out=$(command 2>&1); then echo ok; else echo "failed: $out"; fithe output and whether it worked
Notes
- $(…) is the modern form of backticks: it nests and reads better.
Commands used
mapfile
Each has a page in lore: lore mapfile opens it.
Related recipes
- ask for input in a scriptAsk yes or no, read a password without showing it, or wait for an answer with a time limit.
- check if a file or folder existsTest in a script whether a path exists, is a file, a folder, empty or runnable.
- check if a string contains a textTest in a script whether a string contains, starts with or matches something.
- find the script's own folderInside a script, find the folder the script is in, to reach files next to it.