i have this little piece of code lets say get.sh that sets the date into a variable like this

date=$(date +%b%d%y)

now I want to be able to pass custom date parameter to get.sh like

./get.sh --date=2019-01-01

And on the get.sh to be able to make a check if any parameter is sent get the parameter if not than leave it as it is, so like

if ( isset( dateFromCli ) )
date = datefromCLi
date=$(date +%b%d%y

2 Answers 2


Look at the "Special Parameters" on e.g. the Bash man page. Briefly, you should be able to test ${#} to determine how many command line parameters were provided, and ${1}, ${2}, ${3}, ... to use the individual parameter values.


For your particular problem, this would also work if you are using Bash, shortening your code a little, by allowing you to omit the if construct:


The expression to the right of the equals sign is a special form of parameter expansion, the general form of which is:

${variableName-"default value"}

If the variable under the name variableName is defined, the whole ${} construct expands to the value of the variable.

If it is not defined however, then the construct expands to the default value, to the right of the literal hyphen (-). A variable is considered defined if it was assigned to previously and was not unset afterwards. It is even defined if an empty value was assigned to it.

If you have previously set dateFromCLI to an empty value, you can use the same style of expansion, but with the - substituted by :-. In this case, the default value is also chosen if the named variable is defined, but has a null value (empty string):

${variableName:-"default value"}

Reference: GNU Bash Reference Manual: Shell Parameter Expansion

  • 1
    Thanks but I still dont get it :) This bash thing is driving me crazy Commented Jan 5, 2019 at 15:29
  • No wonder, since it is crazy. Whenever you can, avoid the shell. It is unsafe and messy. What I've provided is a shorthand to get a default value if a variable is not defined. Think of ${varName-default} as a special kind of $varName, with extra rules due to the dash in the middle. The result of the evaluation is not simply the value of varName, a decision is made first. If varName is defined, use its value, otherwise, use the default value.
    – Larry
    Commented Jan 5, 2019 at 15:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .