From cbfb9c394a009b00e7b487663e33d4d6b5d8cd54 Mon Sep 17 00:00:00 2001 From: Gregory Chamberlain Date: Mon, 12 Oct 2020 17:19:52 +0100 Subject: [PATCH] Add section: Filter the argument list --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index 1fd0155..77867a5 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ See something incorrectly described, buggy or outright wrong? Open an issue or s * [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) + * [Filter the argument list](#filter-the-argument-list) * [VARIABLES](#variables) * [Name a variable based on another variable](#name-a-variable-based-on-another-variable) * [ESCAPE SEQUENCES](#escape-sequences) @@ -675,6 +676,31 @@ for dir in ~/Downloads/*/; do done ``` +# Filter the argument list + +This is a general technique for looping over the argument list, dropping +any arguments for which some `` fails. + +``` shell +for arg do + shift + || continue + set -- "$@" "$arg" +done +``` + +**Example:** + +Drop arguments that are not directories. For simple, one-liner +tests like this we can use `&&` instead of `|| continue`. + +``` shell +for arg do + shift + [ -d "$arg" ] && set -- "$@" "$arg" +done +``` + # VARIABLES ## Name and access a variable based on another variable