shell - Bash: How to set a variable from argument, and with a default value -


it pretty clear shell scripting sort of thing can accomplished in huge number of ways (more programming languages) because of different variable expansion methods , programs test , [ , [[, etc.

right i'm looking

dir=$1 or . 

meaning, dir variable should contain either specified in first arg or current directory.

what difference between , dir=${1-.}?

i find hyphen syntax confusing, , seek more readable syntax.

why can't this?

dir="$1" || '.' 

i'm guessing means "if $1 empty, assignment still works (dir becomes empty), invalid command '.' never gets executed."

i see several questions here.

  1. “can write reflects logic”

    yes. there few ways can it. here's one:

    if [[ "$1" != "" ]];     dir="$1" else     dir=. fi 
  2. “what difference between , dir=${1-.}?”

    the syntax ${1-.} expands . if $1 unset, expands $1 if $1 set—even if $1 set empty string.

    the syntax ${1:-.} expands . if $1 unset or set empty string. expands $1 if $1 set other empty string.

  3. “why can't this? dir="$1" || '.'

    because bash, not perl or ruby or other language. (pardon snideness.)

    in bash, || separates entire commands (technically separates pipelines). doesn't separate expressions.

    so dir="$1" || '.' means “execute dir="$1", , if exits non-zero exit code, execute '.'”.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -