Useful Bash Variables

Everytime I write a bash script, I have to look up one of these special bash variables and I always forget which one is which. Jotting it down so that I don’t have to google for them the next time.

  • $@ – all arguments as a big string.
  • $# – number of arguments passed in
  • $? – exit code of the last program
  • $$ – your process ID
  • $! – process ID of last program started w/ ‘&’

Pass Bash Variables to Awk

Bash variables can’t be passed into awk, like one can with a lot of other commands. They need to be declared using the -v option. Here’s a code snippet which shows how.

#!/bin/bash
mainstring="abcdef"
substring="cde"
awk -v a="$mainstring" -v b="$substring" 'BEGIN  { print index(a,b) }'

The above awk command is for locating the position of the first letter of the substring cde within the main string abcdef. In this case the position is 3, which is the position of the character ‘c’ in the main string. The variables $mainstring and $substring are passed into awk by pre-declaring them as a and b respectively.