What are other special variables?

082

In shell scripting, there are several special variables that provide useful information about the script's execution environment. Here are some commonly used special variables:

  1. $0: The name of the script itself.

    echo "Script name: $0"
  2. $1, $2, ..., $N: Positional parameters that represent the arguments passed to the script. $1 is the first argument, $2 is the second, and so on.

    echo "First argument: $1"
    echo "Second argument: $2"
  3. $#: The number of positional parameters (arguments) passed to the script.

    echo "Number of arguments: $#"
  4. $@: All positional parameters as separate words. It treats each argument as a separate entity.

    echo "All arguments: $@"
  5. $*: All positional parameters as a single word. It treats all arguments as a single entity.

    echo "All arguments (single word): $*"
  6. $$: The process ID (PID) of the current shell or script. This can be useful for creating unique temporary files.

    echo "Current process ID: $$"
  7. $?: The exit status of the last command executed. A value of 0 typically indicates success, while any non-zero value indicates an error.

    ls /nonexistentfile
    echo "Last command exit status: $?"
  8. $!: The process ID of the last background command executed. This is useful for job control.

    sleep 10 &
    echo "PID of last background command: $!"
  9. $-: The current options set for the shell. This can provide information about the shell's behavior.

    echo "Current shell options: $-"

These special variables are essential for writing flexible and dynamic shell scripts, allowing you to handle user input, control flow, and manage processes effectively.

0 Comments

no data
Be the first to share your comment!