Bash

Scope

Functions in a POSIX shell have no provision for local variables. Bash does provide for local variables using:

	function foo {
	  local a b c
	  ...
	}

Test

Use either

	$ test [expression]
	or
	$ [ [expression] ]

	$ s1 = s2	# strings s1 and s2 are the same
	$ s1 != s2	# strings s1 and s2 are not the same
	$ n1 -eq n2	# integers n1 and n2 are equal
	$ n1 -ne n2	# integers n1 and n2 are not equal

Complete examples:

	if [ $a -eq $b ]; then
	  echo "equal integers\n"
	fi

	[ "$a" = "$b" ] && echo "equivalent strings\n"
	[ -f /tmp/myfile ] || echo "file not found\n"


Constructs

( execute in a subshell )
{ code block }

[ $a = 2 ] || (echo noa && echo xxx)
[ $a = 2 ] || { echo noa && echo xxx; }
Must have spaces around braces and must have semicolon or newline




Feed a block at the bottom with command output

while read LINE; do
  echo "$LINE"
done < <(command)

The space between < and < is required




Feed a block at the bottom with file input

while read b; do
  echo $b
done < /etc/joe/joerc|grep -v "^#"|grep -v '^$'

This example code also ignores comment and blank lines



Brace Expansion

echo {a,b}{c,d} --> ac ad bc bd
echo {a..d}{e,f} --> ae af be bf ce cf de df
cat {file1,file2,file3} > combined_file # Concatenates the files file1, file2, and file3 into combined_file.
cp /usr/local/bin/file22.{txt,backup} # Copies "/usr/local/bin/file22.txt" to "/usr/local/bin/file22.backup"


Indirect Variable References

a='cat'
cat=123
echo ${!a} --> 123
 -or-
eval echo \$$a --> 123
 -or-
eval a=\$$a
echo $a	--> 123

Send mail to the Webmaster

logo This site best viewed with a browser
Warning: This is a Debian centric site
Many thanks to Debra and Ian Murdock for making Debian possible
First created Dec 14, 2008 ~ Last revised September 05, 2009

Valid XHTML 1.0 Strict Valid CSS!