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

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

问题描述

然而:为什么这个特定的脚本有这个结果?



根据内获取Bash脚本的源目录https://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in#comment16925670_59895\">关于该问题的评论,我使用以下内容一个cron工作:

  DIR = $(pwd)
如果[$ CRON ==true];那么
#如果环境变量$ CRON设置为true,我们可能在cron作业
中,如果[$ PWD ==/];那么
#如果当前的工作目录是root,我们可能在cron工作中
DIR =$(cd$(dirname$ {BASH_SOURCE [0]})& & pwd&& echo x)
DIR =$ {DIR%x}
fi
fi

$ b $ p $然而,我的目录变量($ DIR)以某种方式结束了一个换行符,无论如何,随着$ DIR变量用于创建一个路径,它将中断脚本。为什么是换行?



诚然,我不太熟悉bash脚本和命令替换的细微差别。可能我误解了l0b0脚本的目的。

解决方案

简单:建议的代码是错误的,并且总是添加换行符因为pwd总是打印一个)。



更正的版本将是

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


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.

解决方案

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}

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

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