From d55ed71e50621fbbacf3a7ba4d296a7b46b0c06d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Mon, 15 Jun 2020 22:32:35 +0300 Subject: [PATCH] Note bash temp file and posix mode caveats, add lastpipe recipes --- SC2207.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/SC2207.md b/SC2207.md index d5b7cae..dbaf47a 100644 --- a/SC2207.md +++ b/SC2207.md @@ -11,14 +11,14 @@ array=( $(mycommand) ) If it outputs multiple lines, each of which should be an element: ```sh -# For bash 4.x +# For bash 4.x, must not be in posix mode, may use temporary files mapfile -t array < <(mycommand) -# For bash 3.x+ +# For bash 3.x+, must not be in posix mode, may use temporary files array=() while IFS='' read -r line; do array+=("$line"); done < <(mycommand) -# For ksh +# For ksh, and bash 4.2+ with the lastpipe option enabled (may require disabling monitor mode) array=() mycommand | while IFS="" read -r line; do array+=("$line"); done ``` @@ -26,9 +26,13 @@ mycommand | while IFS="" read -r line; do array+=("$line"); done If it outputs a line with multiple words (separated by spaces), other delimiters can be chosen with IFS, each of which should be an element: ```sh -# For bash +# For bash, uses temporary files IFS=" " read -r -a array <<< "$(mycommand)" +# For bash 4.2+ with the lastpipe option enabled (may require disabling monitor mode) +array=() +mycommand | IFS=" " read -r -a array + # For ksh IFS=" " read -r -A array <<< "$(mycommand)" ```