简体   繁体   English

需要在 bash 脚本中创建文件

[英]Need to chown created file in bash script

I have to run a command in a script as a non-root user, or the command won't run.我必须以非 root 用户身份在脚本中运行命令,否则该命令将无法运行。 However once this is done, I need the subsequent file to be chown'd to the root user.但是,一旦完成,我需要将后续文件 chown'd 给 root 用户。 However, I'm not sure what is the "correct" or best method of doing this.但是,我不确定这样做的“正确”或最佳方法是什么。 Sample:样本:

 sudo -u $usr db export --path="${htmldir}"/ "/home/zzz/backups/${url}_${st}_$(date '+%Y-%m-%d-%H-%M-%S').sql"

Basically the above has various variable substitutions.基本上上面有各种变量替换。 I'm also adding a timestamp to the file.我还在文件中添加时间戳。 What would be the best way to chown that file that has just been created, as it has a timestamp - which could be different if I ran a:什么是 chown 刚刚创建的文件的最佳方式,因为它有一个时间戳 - 如果我运行一个可能会有所不同:

chown root:root "/home/zzz/backups/${url}_${st}_$(date '+%Y-%m-%d-%H-%M-%S').sql"

How do I run a command and place part of that command in a variable - the output file name?如何运行命令并将该命令的一部分放在变量中 - output 文件名?

You should only run the date command once, and store the result in a variable.您应该只运行一次date命令,并将结果存储在一个变量中。 You could either store just the date:您可以存储日期:

curr_date="$(date '+%Y-%m-%d-%H-%M-%S')"
sudo -u $usr db export --path="${htmldir}"/ "/home/zzz/backups/${url}_${st}_${curr_date}.sql"
chown root:root "/home/zzz/backups/${url}_${st}_${curr_date}.sql"

...or save the entire file path in a variable: ...或将整个文件路径保存在变量中:

sql_file="/home/zzz/backups/${url}_${st}_$(date '+%Y-%m-%d-%H-%M-%S').sql"
sudo -u $usr db export --path="${htmldir}"/ "$sql_file"
chown root:root "$sql_file"

Personally, I'd prefer the second since it makes it clearer that it's the same file in both places (and harder to goof and use different paths in the two commands).就个人而言,我更喜欢第二个,因为它更清楚地表明它在两个地方都是同一个文件(并且更难搞砸并在两个命令中使用不同的路径)。 If you needed to use the date for something else as well, I'd actually recommend storing both:如果您还需要将日期用于其他用途,我实际上建议同时存储两者:

curr_date="$(date '+%Y-%m-%d-%H-%M-%S')"
sql_file="/home/zzz/backups/${url}_${st}_${curr_date}.sql"
sudo -u $usr db export --path="${htmldir}"/ "$sql_file"
chown root:root "$sql_file"
someotherCommand "$curr_date"

Oh, and double-quoting the string on the right side of an assignment is optional, but in lots of other contexts using a variable without double-quotes around it can cause trouble, so I tend to double-quote in assignments just for consistency.哦,在赋值右侧的字符串双引号是可选的,但在许多其他上下文中,使用没有双引号的变量会导致麻烦,所以我倾向于在赋值中使用双引号来保持一致性。

You don't need to use sudo to run the command since you are already root您不需要使用 sudo 来运行命令,因为您已经是 root

su -l user -c "db export --path=${htmldir}/ /home/zzz/backups/${url}_${st}_${curr_date}.sql"
chown root:root /home/zzz/backups/${url}_${st}_$(date '+%Y-%m-%d-%H-%M-%S').sql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM