BashPitfalls: common errors that Bash programmers make – Greg’s Wiki
Posted by jpluimers on 2015/12/03
I wish I had seen this years ago, as I’ve always had a hate-hate relationship with many shells on many OS-es.
I’ve included the ToC; read the rest of BashPitfalls: common errors that Bash programmers make – Greg’s Wiki back-to-back. It’s worth it, really.
Bash Pitfalls
This page shows common errors that Bash programmers make. These examples are all flawed in some way.
You will save yourself from many of these pitfalls if you simply always use quotes and never use WordSplitting for any reason! Word splitting is a broken legacy misfeature inherited from the Bourne shell that’s stuck on by default if you don’t quote expansions. The vast majority of pitfalls are in some way related to unquoted expansions, and the ensuing word splitting and globbing that result.
Contents
- for i in $(ls *.mp3)
- cp $file $target
- Filenames with leading dashes
- [ $foo = “bar” ]
- cd $(dirname “$f”)
- [ “$foo” = bar && “$bar” = foo ]
- [[ $foo > 7 ]]
- grep foo bar | while read -r; do ((count++)); done
- if [grep foo myfile]
- if [bar=”$foo”]; then …
- if [ [ a = b ] && [ c = d ] ]; then …
- read $foo
- cat file | sed s/foo/bar/ > file
- echo $foo
- $foo=bar
- foo = bar
- echo <<EOF
- su -c ‘some command’
- cd /foo; bar
- [ bar == “$foo” ]
- for i in {1..10}; do ./something &; done
- cmd1 && cmd2 || cmd3
- echo “Hello World!”
- for arg in $*
- function foo()
- echo “~”
- local varname=$(command)
- export foo=~/bar
- sed ‘s/$foo/good bye/’
- tr [A-Z] [a-z]
- ps ax | grep gedit
- printf “$foo”
- for i in {1..$n}
- if [[ $foo = $bar ]] (depending on intent)
- if [[ $foo =~ ‘some RE’ ]]
- [ -n $foo ] or [ -z $foo ]
- [[ -e “$broken_symlink” ]] returns 1 even though $broken_symlink exists
- ed file <<<“g/d\{0,3\}/s//e/g” fails
- expr sub-string fails for “match”
- On UTF-8 and Byte-Order Marks (BOM)
- content=$(<file)
- for file in ./* ; do if [[ $file != *.* ]]
- somecmd 2>&1 >>logfile
- cmd; (( ! $? )) || die
- y=$(( array[$x] ))
- read num; echo $((num+1))
- IFS=, read -ra fields <<< “$csv_line”
–jeroen






Leave a comment