How does bash script command substitution work?

半腔热情 提交于 2019-12-23 06:23:17

问题


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}


来源:https://stackoverflow.com/questions/24537068/how-does-bash-script-command-substitution-work

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