【问题标题】:Preserving (reconstructing?) single quotes in Bash arguments to script commands在脚本命令的 Bash 参数中保留(重构?)单引号
【发布时间】:2011-01-28 21:37:11
【问题描述】:

我编写了一个 shell 脚本,它可以让我 grep 遍历目录树并在 grep 输出中保留路径。 开始是这样的:

#!/bin/bash
# findjs.sh
# Given a word or argument, greps javascript files from one dir down to the 8th dir down,
# as in: */*.js */*/*.js ... */*/*/*/*/*/*.js 

f="*/*.js"
for p in {1..8}
do
    echo 'Searching '"$f"
    grep -in $1 $f;
    f="*/"$f
done

效果很好。问题是如果我想发送一个多字串作为我的搜索词,它会扩展它们。没关系:

./findjs.sh  aword /var/local/somedir

这不是:

./findjs.sh  'the message' /var/local/somedir

Bash 将 grep 行转移到

grep -in the message /var/local/somedir

我尝试了各种方法来尝试将 $1 用单引号括起来 像这样:

escaped="'\''"
t=$escaped$1$escaped

grep -in $escaped$1$escaped $fp;

双引号中的单引号等等,但是单引号每次都会消失。

我错过了什么?

【问题讨论】:

    标签: bash grep quotes


    【解决方案1】:
    grep "$1" ...
    

    ...应该可以正常工作

    【讨论】:

    • 确实如此。显然错过了显而易见的事情。
    猜你喜欢
    • 2021-11-11
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2016-01-22
    • 2020-04-06
    • 2010-12-12
    相关资源
    最近更新 更多