Bash

From IdeaNet
Jump to navigationJump to search

BASH variable scope in while loop

while read line; do echo "$line"; done < <(cat file.txt)
while read file; do echo "$file"; done <file.txt

character replacement with tr

  • replace a single character with a newline character
cat file|tr "," "\n" # replace every comma with a new line character
  • replace several subsequent identical characters with one occurence of the character
cat file|tr -s " " # replace group of spaces with a single space
  • replace several subsequent identical characters with one occurence of another character
cat file|tr -s " " "," # replace every single space or group of spaces with a comma

internal variables

$$ pid of current bash process
$! pid of last job run in background
$? exit status of last command
$- flags passed to bash (using set)
$# number of command-line arguments
$* all of the positional parameters, seen as a single word
$@ same as $*, but each parameter is a quoted string

associative arrays

$ typeset -A names
$ names=(["Linus"]="Torvalds" ["Richard"]="Stallman")
$ for lastname in "${names[@]}"; do echo $lastname; done
Stallman
Torvalds
$ for firstname in "${!names[@]}"; do echo $firstname; done
Richard
Linus

$ declare -a letters
$ letters=(Z N E)
$ echo "amount of letters: ${#letters[*]}"
amount of letters: 3
$ for letter in "${letters[@]}"; do echo $letter; done
Z
N
E

indirect expansion

$ myvar="the content of myvar"
$ another_name="myvar"
$ echo ${!another_name}
the content of myvar

some tips

description code result
right pattern deletion str="bash is great"
echo ${str%%is*}
bash
left pattern deletion str="bash is great"
echo ${str##*is}
great
set upper case str="bash is great"
echo ${str^^}
BASH IS GREAT
set down case str="BASH IS GREAT"
echo ${str,,}
bash is great
pattern subsitution str="bash is great, really great"
echo ${str/great/fantastic}
bash is fantastic, really great
global pattern subsitution str="bash is great, really great"
echo ${str//great/fantastic}
bash is fantastic, really fantastic

shell parameter expansion

Below word can be one of:

  • tilde expansion
  • parameter expansion
  • command substitution
  • arithmetic expansion
  • string


  • when $parameter is null or unset => substitute with the expansion of word:
${parameter:-word}
  • when $parameter is null or unset => assigns the expansion of word to parameter, substitute with $parameter
${parameter:=word}  
  • when $parameter is null or unset => print to stderr the expansion of word and exit
${parameter:?word}
  • when $parameter is not null or set => substitute with the expansion of word, otherwise substitute with nothing
${parameter:+word}