Bash Script: built-in (or predefined) variables

sneh srivastavasneh srivastava
2 min read

In Bash, there are several built-in (or predefined) variables that hold information about the current shell session, scripts, and the environment. Some of the most common ones are listed below. While there isn't an exact number, Bash includes dozens of these variables.

Some Common Built-in Variables:

  1. $0: The name of the script or shell.

  2. $1, $2, ... $n: Positional parameters that represent arguments passed to the script.

  3. $#: The number of positional parameters (arguments) passed to the script.

    • Example: If ./script.sh arg1 arg2, then $# will be 2.
  4. $@: All the positional parameters (arguments) as a single string.

    • Example: ./script.sh arg1 arg2, $@ will return "arg1 arg2".
  5. $*: All the positional parameters as a single word.

    • Example: ./script.sh arg1 arg2, $* will return "arg1 arg2".
  6. $?: The exit status of the last command.

    • Example: If the previous command was successful, $? will return 0.
  7. $$: The process ID (PID) of the current shell.

    • Example: echo $$ will print the PID of the running script.
  8. $!: The process ID (PID) of the last background command.

    • Example: command & echo $! will give you the PID of command run in the background.
  9. $-: The current options set for the shell.

    • Example: If running the shell with options like -x (debugging), $- will include x.
  10. $_: The last argument of the previous command.

    • Example: If the previous command was echo hello world, $_ will be world.

Special Environment Variables:

  1. HOME: The current user’s home directory.

    • Example: /home/user
  2. USER: The current logged-in user.

    • Example: user
  3. SHELL: The shell being used.

    • Example: /bin/bash
  4. PATH: The system’s search path for executable files.

    • Example: /usr/local/bin:/usr/bin:/bin
  5. PWD: The current working directory.

    • Example: /home/user/directory
  6. OLDPWD: The previous working directory.

    • Example: The directory you were in before the current one.
  7. IFS: Internal Field Separator, used for word splitting.

    • Example: By default, it’s a space, tab, and newline.
  8. LANG: The current language/locale settings.

    • Example: en_US.UTF-8

Other Less Common Built-in Variables:

  1. UID: The user ID of the current user.

  2. PS1: The primary prompt string.

  3. PS2: The secondary prompt string.

  4. HOSTNAME: The name of the current host.

Conclusion:

While there isn't a strict count since the number of built-in variables can vary depending on the environment, there are dozens of important ones that come pre-defined in most Bash environments. The variables listed above cover the most commonly used ones in shell scripting.

0
Subscribe to my newsletter

Read articles from sneh srivastava directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sneh srivastava
sneh srivastava