2

I couldn't find an example online but I'm sure I've seen shell coders use ${1:--} to accept user input. Here's an example:

#!/bin/bash

var="${1:--}"
echo "$var"

Then, run it:

$ ./test.sh "this is a test"

My question is: how is using "${1:--}" to accept user input different from "$1"?

  • What do you mean by "user input"? Supplied on the command line, or read from the terminal? – RudiC Oct 28 '18 at 14:36
1

${1:--} will expand to the string "-" if there is no parameter one or if the parameter is empty.

So ./test.sh "" will return the string "-" as will the command ./test.sh This is considered to be a useful default in many circumstances where an argument of "-" can mean stdin or stdout. Also it makes sure scripts don't break when a parameter is not explicitly set.

0

Under bash's parameter expansion you can use default value of the variable and this is what ${1:--} does to thirst command argument, namely it assigns value - if and only if $1 is unset or null. It works with any other parameters too, test this example:

echo "${var:-X}"   # var is not defined so X will be echoed
var=Y              # lets define var
echo "${var:-X}"   # var is defined so its value Y will be printed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.