一个例子明白shell变量替换问题

脚本名为value.sh

 #!/bin/bash

 
var()
{
    echo '${file-my.file.txt}:' ${file-my.file.txt}
    echo '${file:-my.file.txt}:' ${file:-my.file.txt}
    echo '${file+my.file.txt}:' ${file+my.file.txt}
    echo '${file:+my.file.txt}:' ${file:+my.file.txt}
    echo '${file=my.file.txt}:' ${file=my.file.txt}
    echo '${file:=my.file.txt}:' ${file:=my.file.txt}
    echo '${file?my.file.txt}:' ${file?my.file.txt}
    echo '${file:?my.file.txt}:' ${file:?my.file.txt}
}
 
file=$1
echo "variable is not null"
var
 
echo -------------------------------------------------------------
echo "varable is null"
file=$2
var
 
echo -----------------------------------------------------------------------------
echo "variable is unset not variable"
unset file
var
 
运行sh value.sh a 得到如下结果,这样就可以明白各自的意思了
variable is not null
${file-my.file.txt}: a
${file:-my.file.txt}: a
${file+my.file.txt}: my.file.txt
${file:+my.file.txt}: my.file.txt
${file=my.file.txt}: a
${file:=my.file.txt}: a
${file?my.file.txt}: a
${file:?my.file.txt}: a
-------------------------------------------------------------
varable is null
${file-my.file.txt}:
${file:-my.file.txt}: my.file.txt
${file+my.file.txt}: my.file.txt
${file:+my.file.txt}:
${file=my.file.txt}:
${file:=my.file.txt}: my.file.txt
${file?my.file.txt}: my.file.txt
${file:?my.file.txt}: my.file.txt
-----------------------------------------------------------------------------
variable is unset not variables
${file-my.file.txt}: my.file.txt
${file:-my.file.txt}: my.file.txt
${file+my.file.txt}:
${file:+my.file.txt}:
${file=my.file.txt}: my.file.txt
${file:=my.file.txt}: my.file.txt
${file?my.file.txt}: my.file.txt
${file:?my.file.txt}: my.file.txt

 

你可能感兴趣的:(shell,shell变量替换)