Bash: Difference between revisions
From Federal Burro of Information
Jump to navigationJump to search
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
==Swapping stdin and stdout == | == Swapping stdin and stdout == | ||
command 3>&1 1>&2 2>&3 | command 3>&1 1>&2 2>&3 | ||
== extracting vars from strings == | |||
<pre> | |||
#!/usr/bin/env bash | |||
str1="the value of var1=test, the value of var2=testing, the final value of var3=testing1" | |||
re='(^|[[:space:]])([[:alpha:]][[:alnum:]]*)=([^, ]+)([, ]|$)(.*)' | |||
remaining=$str1 | |||
while [[ $remaining =~ $re ]]; do | |||
varname=${BASH_REMATCH[2]} | |||
value=${BASH_REMATCH[3]} | |||
remaining=${BASH_REMATCH[5]} | |||
printf -v "$varname" %s "$value" | |||
done | |||
# show current values to demonstrate that variables were really assigned | |||
declare -p var1 var2 var3 | |||
</pre> | |||
== Also See == | == Also See == |
Revision as of 15:35, 24 December 2019
Swapping stdin and stdout
command 3>&1 1>&2 2>&3
extracting vars from strings
#!/usr/bin/env bash str1="the value of var1=test, the value of var2=testing, the final value of var3=testing1" re='(^|[[:space:]])([[:alpha:]][[:alnum:]]*)=([^, ]+)([, ]|$)(.*)' remaining=$str1 while [[ $remaining =~ $re ]]; do varname=${BASH_REMATCH[2]} value=${BASH_REMATCH[3]} remaining=${BASH_REMATCH[5]} printf -v "$varname" %s "$value" done # show current values to demonstrate that variables were really assigned declare -p var1 var2 var3