Bash

From Federal Burro of Information
Jump to navigationJump to search

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:

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