diff options
author | Dylan Araps <dylan.araps@gmail.com> | 2019-09-19 12:55:33 +0300 |
---|---|---|
committer | Dylan Araps <dylan.araps@gmail.com> | 2019-09-19 12:55:33 +0300 |
commit | cca0abedae0c49bf65990e11369e944318cf4f24 (patch) | |
tree | 9dc506f34cbba165afae2defaaa9ebbc249f0ff5 | |
parent | 8b7ce63498beeaab9e9d12c111aa2b69aba7908d (diff) | |
download | pure-sh-bible-cca0abedae0c49bf65990e11369e944318cf4f24.tar.gz pure-sh-bible-cca0abedae0c49bf65990e11369e944318cf4f24.zip |
docs: update
-rw-r--r-- | README.md | 62 |
1 files changed, 62 insertions, 0 deletions
@@ -25,6 +25,11 @@ align="center">A collection of pure POSIX sh alternatives to external processes. * [FILE PATHS](#file-paths) * [Get the directory name of a file path](#get-the-directory-name-of-a-file-path) * [Get the base-name of a file path](#get-the-base-name-of-a-file-path) +* [LOOPS](#loops) + * [Loop over a (*small*) range of numbers](#loop-over-a-small-range-of-numbers) + * [Loop over a variable range of numbers](#loop-over-a-variable-range-of-numbers) + * [Loop over the contents of a file](#loop-over-the-contents-of-a-file) + * [Loop over files and directories](#loop-over-files-and-directories) * [ESCAPE SEQUENCES](#escape-sequences) * [Text Colors](#text-colors) * [Text Attributes](#text-attributes) @@ -410,6 +415,63 @@ $ basename ~/Pictures/Downloads/ Downloads ``` +# LOOPS + +## Loop over a (*small*) range of numbers + +Alternative to `seq` and only suitable for small and static number ranges. The number list can also be replaced with a list of words, variables etc. + +```shell +# Loop from 0-10. +for i in 0 1 2 3 4 5 6 7 8 9 10; do + printf '%s\n' "$i" +done +``` + +## Loop over a variable range of numbers + +Alternative to `seq`. + +```shell +# Loop from var-var. +start=0 +end=50 + +while [ "$start" -le "$end" ]; do + printf '%s\n' "$start" + start=$((start+1)) +done +``` + +## Loop over the contents of a file + +```shell +while read -r line; do + printf '%s\n' "$line" +done < "file" +``` + +## Loop over files and directories + +Don’t use `ls`. + +```shell +# Greedy example. +for file in *; do + printf '%s\n' "$file" +done + +# PNG files in dir. +for file in ~/Pictures/*.png; do + printf '%s\n' "$file" +done + +# Iterate over directories. +for dir in ~/Downloads/*/; do + printf '%s\n' "$dir" +done +``` + # ESCAPE SEQUENCES Contrary to popular belief, there is no issue in utilizing raw escape sequences. Using `tput` abstracts the same ANSI sequences as if printed manually. Worse still, `tput` is not actually portable. There are a number of `tput` variants each with different commands and syntaxes (*try `tput setaf 3` on a FreeBSD system*). Raw sequences are fine. |