【发布时间】:2012-09-02 19:41:06
【问题描述】:
我希望能够编写一个函数 su_mt_user,它(目前)看起来像这样:
su_mt_user() {
su someuser -c "$*"
}
目标是能够像这样使用它:
su_mt_user mt-auth --stuff etc
它将以用户someuser 的身份运行命令mt-auth --stuff etc。当前版本适用于这个特定的命令,但对于这样的命令却失败了:
some_filename_with_spaces="/home/user/hello there i like spaces in filenames.txt"
su_mt_user stat "$some_filename_with_spaces"
这会失败并出现以下错误:
stat: cannot stat '/home/user/hello': No such file or directory
stat: cannot stat 'there': No such file or directory
stat: cannot stat 'i': No such file or directory
stat: cannot stat 'like': No such file or directory
stat: cannot stat 'spaces': No such file or directory
stat: cannot stat 'in': No such file or directory
stat: cannot stat 'filenames.txt': No such file or directory
我认为发生此错误是因为即使 $some_filename_with_spaces 被正确地作为一个参数传递给 su_mt_user 函数,该函数将其扩展为带有 "$*" 的多个参数。
我也试过这个,反复试验:
su_mt_user() {
su someuser -c "$0 $@"
}
但这也失败了(/usr/bin/stat: cannot execute binary file(什么?))
当然,stat "$some_filename_with_spaces" 在当前用户和someuser 用户中都按预期工作。
这看起来需要进行一些转义,但是 bash 知道该怎么做吗?需要手动替换吗?如果是,哪些字符需要转义?
【问题讨论】:
标签: bash function escaping arguments su