在 bash 中,如何在字符串中插入 $(...)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23655580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:26:27  来源:igfitidea点击:

In bash, how do I interpolate $(...) in a string?

bashshellstring-interpolation

提问by Hoytman

I am attempting to write a bash script that performs a mysqldump on my live site's database, then adds and commits the dump to a git repository. Here is what I have so far (stored in a .sh file which is called by a crontab entry):

我正在尝试编写一个 bash 脚本,该脚本在我的实时站点的数据库上执行 mysqldump,然后将转储添加并提交到 git 存储库。这是我到目前为止所拥有的(存储在由 crontab 条目调用的 .sh 文件中):

/usr/bin/mysqldump --skip-comments --skip-dump-date -u [user] -p[pass] database | gzip > /var/www/site/backup/database.sql.gz
cd var/www/site/backup && git add *
cd var/www/site/backup && git commit -m 'Database $(date +%a %H:%M %h %d %Y)'

My crontab entry looks like this:

我的 crontab 条目如下所示:

0,20,40 8-22 * * * /var/www/site/backup/script.sh

I can see that this script does dump the database, but does not add or commit the file to git. Is there something that I am missing?

我可以看到这个脚本确实转储了数据库,但没有将文件添加或提交到 git。有什么我想念的吗?

Edit =================================

编辑 ================================

I made the following changes and the commit works:

我进行了以下更改并且提交有效:

cd /var/www/site/backup && /usr/bin/git add *
cd /var/www/site/backup && /usr/bin/git commit -m 'Database $(date +%a %H:%M %h %d %Y)'

However, the date does not get calculated.

但是,不会计算日期。

Edit =================================

编辑 ================================

Latest Revisions, including (most of) the recommendations

最新修订,包括(大部分)建议

/usr/bin/mysqldump --skip-comments --skip-dump-date -u [user] -p[pass] database > /var/www/site/backup/database.sql
cd var/www/site/backup
/usr/bin/git add *
/usr/bin/git commit -m "Internal Forms Live Database Dump Stored $(date '+%a %H:%M %h %d %Y')"

回答by kostix

$(...)and other forms of substitutions are not interpolated in single-quoted strings.

$(...)其他形式的替换不会插入到单引号字符串中

So if you want your date calculated, do

所以如果你想计算你的日期,做

git commit -m "Database $(date '+%a %M:%H %h %d %Y')"

that is, the whole message string is double-quoted to allow $(...)to be interpolated while the argument to dateis in single quotes to make it a single argument (passed to date).

也就是说,整个消息字符串被双引号括起来以允许$(...)插入,而 to 的参数date在单引号中以使其成为单个参数(传递给date)。