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.
“can write reflects logic”
yes. there few ways can it. here's one:
if [[ "$1" != "" ]]; dir="$1" else dir=. fi“what difference between ,
dir=${1-.}?”the syntax
${1-.}expands.if$1unset, expands$1if$1set—even if$1set empty string.the syntax
${1:-.}expands.if$1unset or set empty string. expands$1if$1set other empty string.“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 “executedir="$1", , if exits non-zero exit code, execute'.'”.
Comments
Post a Comment