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.
shelldevelopment
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.
ask for input in a script
Ask yes or no, read a password without showing it, or wait for an answer with a time limit.
check if a file or folder exists
Test in a script whether a path exists, is a file, a folder, empty or runnable.
check if a string contains a text
Test in a script whether a string contains, starts with or matches something.
find the script's own folder
Inside a script, find the folder the script is in, to reach files next to it.