Bash: Difference between revisions

From Federal Burro of Information
Jump to navigationJump to search
No edit summary
No edit summary
 
(3 intermediate revisions by the same user not shown)
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 ==
example 1:
<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>
example 2:
extract the --port=XX section from what was handed to the script, where XX is a number.
<pre>
#!/bin/bash
#re="--port=(.*?) "
re="--port=([0-9]*?) "
if [[ $@ =~ $re ]]; then
echo "match"
echo zero ${BASH_REMATCH[0]}
echo one ${BASH_REMATCH[1]}
echo two ${BASH_REMATCH[2]}
echo three ${BASH_REMATCH[3]}
else
echo "no match"
fi
</pre>


== Also See ==
== Also See ==


[[.bachrc]]
[[.bashrc]]


[[Stupid Shell Tricks]]
[[Stupid Shell Tricks]]

Latest revision as of 18:16, 31 December 2019

Swapping stdin and stdout

command 3>&1 1>&2 2>&3 

extracting vars from strings

example 1:

#!/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

example 2:

extract the --port=XX section from what was handed to the script, where XX is a number.

#!/bin/bash

#re="--port=(.*?) "
re="--port=([0-9]*?) "

if [[ $@ =~ $re ]]; then
 echo "match"
 echo zero ${BASH_REMATCH[0]}
 echo one ${BASH_REMATCH[1]}
 echo two ${BASH_REMATCH[2]}
 echo three ${BASH_REMATCH[3]}
else
 echo "no match"
fi

Also See

.bashrc

Stupid Shell Tricks