【问题标题】:Shell script fails when trying to set the date尝试设置日期时,Shell 脚本失败
【发布时间】:2011-08-24 21:28:17
【问题描述】:

使用基本的 shell 脚本,例如

USER=$1
CMD=$2

/usr/bin/sudo -u $USER $CMD

我可以跑

# ./script.sh root "/bin/echo 'apple pie'"
'apple pie'

但是尝试改为:

#/script.sh root "/bin/date -s '2011-08-24 15:24:30'"
date: the argument `15:24:30\'' lacks a leading `+';
when using an option to specify date(s), any non-option
argument must be a format string beginning with `+'
Try `date --help' for more information.

我可以通过手动输入复制日期错误

/bin/date -s \'2011-08-24 15:24:30\'
date: the argument `15:24:30\'' lacks a leading `+';
when using an option to specify date(s), any non-option
argument must be a format string beginning with `+'
Try `date --help' for more information.

所以我在这个脚本中使用日期的问题是单引号会自动转义哪个日期不喜欢。我可以将脚本更改为基于 $1 $2 $3 "$4" 但这会消除此脚本的通用性(本文已对其进行了简化)。

有什么方法可以使这种性质的脚本支持日期大小写而不需要特殊的大小写?

【问题讨论】:

    标签: bash shell scripting


    【解决方案1】:

    试试这个:

    USER=$1
    shift
    
    /usr/bin/sudo -u $USER "$@"
    

    “$@”保留引号,您应该像这样运行脚本:

    ./script.sh root /bin/echo 'apple pie'
    

    注意没有双引号。

    【讨论】: