代码之家  ›  专栏  ›  技术社区  ›  anthonybell

bash导出表达式而不展开?

  •  1
  • anthonybell  · 技术社区  · 11 年前

    我想做以下事情

    export LOGS=//server/log_files/2014_*/server_{1,2,3}

    所以我可以做一些类似的事情

    grep 'Exception' $LOGS/log.txt

    我也尝试了别名,但无法使其不扩展。

    我怎么能做到这一点?

    2 回复  |  直到 11 年前
        1
  •  1
  •   choroba    11 年前

    没有 export ,赋值的右侧既不经过路径也不经过大括号展开。

    具有 出口 但是,执行了支撑扩展。可以通过引用以下值来防止:

    export LOGS='//server/log_files/2014_*/server_{1,2,3}'
    

    但是,如果要使用这样的值,则必须使用 eval :

    eval grep 'Exception' $LOGS/log.txt
    
        2
  •  1
  •   gniourf_gniourf    11 年前

    你需要扩展地球仪。这是这里最干净、语义最正确的,因为您希望匹配文件名。由于我过于迂腐,我认为大括号扩展不是完成任务的正确工具。

    # This defines a string that will glob
    # No pathname expansions are performed at this step
    logs_glob='//server/log_files/2014_*/server_@(1|2|3)'
    
    # You need to activate extended globs with extglob
    # To have a failure when no files match the glob, you need failglob
    shopt -s failglob extglob
    
    # Unquoted variable $logs_glob, as pathname expansion is desirable
    grep 'Exception' $logs_glob
    

    有些人会认为,使用glob技术,你无法正确处理名称中的空格。事实上,您有两种方法: ? 作为通配符(这将匹配 任何 字符,因此特别是空格)或使用字符类 [[:space:]] 。此字符类将匹配任何空格(常规空格、换行符、制表符等)


    另一种技术是使用数组,仍然使用扩展的globs。我认为这更干净。

    shopt -s extglob nullglob
    
    # This will populate array with all matching filenames.
    # If no matches, array is empty (since we shopted nullglob)
    logs_array=( //server/log_files/2014_*/server_@(1|2|3) )
    
    # Before you launch you command with the array, make sure it's not empty:
    if ((${#logs_array[@]}!=0)); then
        # Observe the quotes for the expansion of the array
        grep 'Exception' "${logs_array[@]}"
    fi