Home > Net >  Shell script: how to read an optional argument. If the argument does not exist, then use a default v
Shell script: how to read an optional argument. If the argument does not exist, then use a default v

Time:01-24

I want to write a shell script that can have an optional argument and if there is no optional argument, then uses a default value. Example: if sys.argv[1].exists() ip = sys.argv[1] else ip = '10.9.2.16'

CodePudding user response:

I'll assume that you've selected the correct tag and are submitting a question about Unix/Linux command line interpreters, and that the example code you wrote was a pseudocode example to explain the desired behavior.

From the manpage for bash, in the "Parameter Expansion" section, it clearly indicates how to do this with any variable, not just positional parameters:

${parameter:-word}

   Use Default Values.  If parameter is unset or null, 
   the expansion of word is substituted.
   Otherwise, the value of parameter is substituted.

This will work for POSIX shell as well, and all dialects of shell script that I know of. So for your example, you could use:

#!/bin/sh
ip=${1:-10.9.2.16}
echo "IP is $ip"

/path/to/script.sh would output: IP is 10.9.2.16. /path/to/script.sh 8.8.8.8 would output: IP is 8.8.8.8.

If you mean that you want $1 to be optional, but that you want other arguments after it, you could explicitly omit the first argument and allow it to fallback to the default by calling the script with a pair of quotes (single or double) in place of the first argument. For example, with the script:

#!/bin/sh
ip=${1:-10.9.2.16}
echo "IP is $ip"
echo "Your second argument is $2"

Calling it like /path/to/script.sh "" quux would output:

IP is 10.9.2.16
Your second argument is quux

CodePudding user response:

As Wilson commented, In shell scripting you can use the ${parameter:-default} syntax to read an optional argument and use a default value if the argument does not exist. Here is an example:

optional_arg=${1:-default_value}
echo "The value of the optional argument is: $optional_arg"

This sets the variable optional_arg to the value of the first argument passed to the script ($1), or the default value "default_value" if the first argument is not provided.

You can also use if statement with [ -z "$variable" ] to check if variable is empty or not.

if [ -z "$optional_arg" ]; then
   optional_arg="default_value"
fi
  • Related