如何bash脚本命令替换工作? [英] How does bash script command substitution work?

查看:175
本文介绍了如何bash脚本命令替换工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

和:为什么这个特殊的脚本有这样的结果?

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

从<一个href=\"http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in\">Can一个Bash脚本告诉哪个目录下的存储?,基于用户l0b0在<一个提供了一些code片段href=\"http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in#comment16925670_59895\">his对这个问题发表评论,我用一个cron作业以下内容:

From Can a Bash script tell what directory it's stored in?, 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

不过,我的目录变量($ DIR)以某种方式后,新行,无论如何,它打破了脚本$ DIR变量用于创建路径的任何时间结束。为什么换行吗?

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?

诚然,我不是太熟悉的bash脚本和命令替换的细微差别。这可能是我误会背后l0b0的剧本的目的。

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.

推荐答案

简单:建议code是错误的,总是添加一个换行符(因为PWD始终打印一个)

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

修正后的版本将是

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

这篇关于如何bash脚本命令替换工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆