2017年5月18日 星期四

[Linux 常見問題] Assigning default values to shell variables with a single command in bash

Source From Here 
Question 
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.: 
  1. if [ -z "${VARIABLE}" ]; then   
  2.     FOO='default'  
  3. else   
  4.     FOO=${VARIABLE}  
  5. fi  
I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.: 
  1. FOO=${ ${VARIABLE} : 'default' }  
(though I know that won't work...
Am I crazy, or does something like that exist? 

How-To 
There are two ways to carry out your request: 
1. ${variable:-'defaultValue'} : When variable is not defined or as None, temporally assign 'defaultValue' to it right in that line. Afterword, the variable is still kept as original state.
2. ${variable:='defaultValue'} : When variable doesn't exist or as None, then assign 'defaultValue' to it and the variable will carry the assigned default value among whole script.

For example, let's do experiment with a simple shell script: 
- test.sh 
  1. #!/bin/sh  
  2.   
  3. echo "variable=${variable:-'defaultValue1'}"  
  4. echo "variable=${variable}"  
  5. echo "varialbe=${variable:='defaultValue2'}"  
  6. echo "variable=${variable}"  
Testing it this way: 
# ./test.sh
variable='defaultValue1'
variable=
varialbe='defaultValue2'
variable='defaultValue2'

# variable='test' ./test.sh
variable=test
variable=test
varialbe=test
variable=test


Supplement 
[Linux 文章收集] 變數值代換 (variables substitution) 精簡筆記

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...