简体   繁体   English

Shell脚本 - 变量中的空格?

[英]Shell scripting - spaces in variables?

Here's the problem I have with my bash script: 这是我的bash脚本遇到的问题:

    date1=(`date -d @$startdate`)
    date2=(`date -d @$enddate`)

    touch --date="$date1" /tmp/newerthan
    touch --date="$date2" /tmp/olderthan

Since the words returned by the date -d command contain spaces, the only thing that gets processed by the touch --date="$var" command is the first word (which is "Mon", "Tue", "Wed"... etc), so it doesn't work properly. 由于date -d命令返回的单词包含空格,因此touch --date="$var"命令处理的唯一内容是第一个单词(“Mon”,“Tue”,“Wed”)。 ..等),所以它不能正常工作。

How can I work around this problem and be able to get the subsequent lines to process the entire string? 我如何解决这个问题,并能够让后续行处理整个字符串?

You've used an array assignment in: 您在以下位置使用了数组赋值:

date1=(`date -d @$startdate`)

Either use plain backquotes (definitely not the preferred technique, though): 要么使用简单的反引号(绝对不是首选技术):

date1=`date -d @$startdate`

Or (much better) use $(...) : 或者(更好)使用$(...)

date1=$(date -d @$startdate)

Or, at a pinch (there'd have to be a good reason), use this to copy the whole array into the argument to touch : 或者,在紧要关头(必须有一个很好的理由),使用它将整个数组复制到要touch的参数中:

touch --date="${date1[*]}" /tmp/newerthan

You might want to consider double quotes around @$startdate , too. 您可能还想考虑@$startdate周围的双引号。

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

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