How are parameters passed in the shell in Linux?
In Linux, you can pass parameters to a shell script using the following methods:
- Positional parameters: Arguments can be passed through the command line after the shell script. These arguments can be accessed in the script using special variables. For example, if the script is named script.sh, parameters can be passed using the command ./script.sh arg1 arg2, and then accessed in the script using $1 and $2.
- Command line options: Use the getopts command to handle command line options. The getopts command is used to parse command line options and arguments, providing a simple way to deal with them. You can use the getopts command in scripts to retrieve command line options and arguments.
- Environment variables: Parameters can be passed in scripts using environment variables. The export command can be used to set a variable as an environment variable, and then the value of the environment variable can be obtained in the script using the form $VAR.
- Standard input: Parameters can be passed to the script as standard input. Parameters can be passed to the script using redirection or piping. For example, parameters can be passed to the script using echo arg1 arg2 | ./script.sh.
These are common methods for passing parameters to a shell script in Linux, you can choose the most suitable method according to your needs.