How to obtain parameters in the shell?

In the shell, you can obtain parameters through various methods.

  1. To access positional parameters, use $ followed by a number. $0 represents the script itself, $1 represents the first argument, $2 represents the second argument, and so on. For example, $0 retrieves the script name and $1 retrieves the first argument.
  2. To obtain all parameters, use $@ or $*. $@ represents a list of all parameters, each enclosed in quotation marks. $* represents a string of all parameters, separated by the value of the IFS environment variable.
  3. Use $# to get the number of parameters. $# represents the number of parameters passed to the script or function.
  4. Use $? to retrieve the exit status of the previous command. A value of 0 for $? indicates that the previous command executed successfully, while a non-zero value indicates failure.
  5. Move parameters using the shift command. This command shifts all parameters to the left by one position, moving the value of $2 to $1, the value of $3 to $2, and so on.
  6. Use getopts to parse command line options. getopts is a built-in shell command that can be used to parse command line options and parameters.

These techniques can be used in shell scripts to retrieve command line arguments and perform corresponding operations.

bannerAds