1. $(command)
2. `command`
範例:
#!/bin/sh
current_date1=$(date +%Y%m%d)
folder_name1=model_${current_date1}
echo "\$folder_name1 = ${folder_name1}"
current_date2=`date +%Y%m%d`
folder_name2=model_${current_date2}
echo "\$folder_name2 = ${folder_name2}"
$folder_name1 = model_20171112
$folder_name2 = model_20171112
注意:
Command Substitution 的結果只有 command 的 stdout 不包含 stderr,底下範例利
用 declare -p 指令在變數存在時會輸出到 stdout,不存在時會輸出到 stderr 的行為
做實驗。範例中有宣告 var1 但是沒有宣告 var2。
範例:
#!/bin/sh
var1=
if [ "$(declare -p var1)" == "" ]; then
echo "The result of \$(declare -p var1) is empty."
else
echo "The result of \$(declare -p var1) is NOT empty."
fi
if [ "$(declare -p var2)" == "" ]; then
echo "The result of \$(declare -p var2) is empty."
else
echo "The result of \$(declare -p var2) is NOT empty."
fi
The result of $(declare -p var1) is NOT empty.
./cmd_substitution.sh: line 10: declare: var2: not found
The result of $(declare -p var2) is empty.
備註:
如果不想要看到 command 往 stderr 的輸出,如上面結果 not found 那一行。
可以將 stderr 導向到 /dev/null,如下範例。
if [ "$(declare -p var2 2>/dev/null)" == "" ]; then
沒有留言:
張貼留言