Assigning default values to shell variables with a

2019-01-03 00:41发布

I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:

if [ -z "${VARIABLE}" ]; then 
    FOO='default'
else 
    FOO=${VARIABLE}
fi

I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:

FOO=${ ${VARIABLE} : 'default' }

(though I know that won't work...)

Am I crazy, or does something like that exist?

标签: bash shell
9条回答
爷的心禁止访问
2楼-- · 2019-01-03 01:04

For command line arguments:

VARIABLE=${1:-DEFAULTVALUE}    

which assigns to VARIABLE the value of the 1st argument passed to the script or the value of DEFAULTVALUE if no such argument was passed.

查看更多
来,给爷笑一个
3楼-- · 2019-01-03 01:09

see here under 3.5.3(shell parameter expansion)

so in your case

${VARIABLE:−default}
查看更多
我只想做你的唯一
4楼-- · 2019-01-03 01:09

Here is an example

#!/bin/bash

default='default_value'
value=${1:-$default}

echo "value: [$value]"

save this as script.sh and make it executable. run it without params

./script.sh
> value: [default_value]

run it with param

./script.sh my_value
> value: [my_value]
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-03 01:10

Then there's the way of expressing your 'if' construct more tersely:

FOO='default'
[ -n "${VARIABLE}" ] && FOO=${VARIABLE}
查看更多
地球回转人心会变
6楼-- · 2019-01-03 01:11

Even you can use like default value the value of another variable

having a file defvalue.sh

#!/bin/bash
variable1=$1
variable2=${2:-$variable1}

echo $variable1
echo $variable2

run ./defvalue.sh first-value second-value output

first-value
second-value

and run ./defvalue.sh first-value output

first-value
first-value
查看更多
Fickle 薄情
7楼-- · 2019-01-03 01:14

Very close to what you posted, actually:

FOO=${VARIABLE:-default}  # If variable not set or null, use default.

Or, which will assign default to VARIABLE as well:

FOO=${VARIABLE:=default}  # If variable not set or null, set it to default.
查看更多
登录 后发表回答