How does bash script command substitution work?

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

And: "Why does this particular script have this outcome?"

From Getting the source directory of a Bash script from within, based on some code snippets offered by user l0b0 in his comment on that question, I used the following for a cron job:

DIR=$(pwd) if [ $CRON == "true" ]; then   # If the environment variable $CRON is set to true, we're probably in a cron job   if [ $PWD == "/" ]; then     # And if the current working directory is root, we're probably in a cron job     DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd && echo x)"     DIR="${DIR%x}"   fi fi 

However, my directory variable ($DIR) somehow ends up with a newline after it anyway, which breaks the script any time the $DIR variable is used to create a path. Why is the newline there?

Admittedly, I'm not overly familiar with the nuances of bash scripting and command substitution. It is possible I misunderstood the purpose behind l0b0's script.

回答1:

Simple: the suggested code is wrong and always adds a line feed (because pwd always prints one).

The corrected version would be

dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && printf "%sx" "$PWD")" dir=${dir%x} 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!