小编dim*_*ech的帖子

如何从多个文本源的第一行创建数组?

我有一组文件路径,每个文件都有几行文本。我想生成一个数组,其中填充了每个文件的第一行,如下所示:

# this.txt first line is [Test this]
# another.txt first line is [Test another]
paths=(
  ./this/path/this.txt
  ./another/path/another.txt
)

for i in ${paths[@]}; do
  read -r line < $i
  lines+=$line
done
Run Code Online (Sandbox Code Playgroud)

我的数组中最多只有一个值。我似乎无法从 for 循环中获取我正在寻找的数组。我尝试了很多变体,但很难弄清楚我哪里出错了。

bash array shell-script

8
推荐指数
1
解决办法
681
查看次数

如何使用函数返回作为 if else then 快捷方式的条件?

在某些情况下,函数需要执行并返回给调用者,这对我有用。

if tst; then
    echo "success"
else
    echo "failure"
fi

function tst () {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,我似乎无法使用快捷语法来做到这一点。我已经尝试了以下语句的多种组合,包括测试 if [[ tst = true ]] 或 if it = "0" 但我一直无法弄清楚。

[[ tst ]] && echo "success" || echo "failure"
Run Code Online (Sandbox Code Playgroud)

使用 bash 快捷语法在 if 条件下测试函数的正确方法是什么?

bash shell-script

6
推荐指数
2
解决办法
2万
查看次数

如何解析其值可能包含某些字符的 ini 文件?

我已经看过几个 bash ini 解析脚本,并且我已经看到这个脚本在这里使用了几次,所以我想看看它是否适合我。看起来它会多次逐行读取 ini 文件,并且每次传递都会逐步构造一个最终被评估的函数。它适用于某些特殊字符,但不适用于其他字符。如果文件中的值包含单引号或大于/小于符号,则脚本返回语法错误。其他符号也会产生意想不到的结果。遇到这些字符时我该如何处理?

这是解析ini的函数。

#!/usr/bin/env bash
cfg_parser ()
{
    ini="$(<$1)"                # read the file
    ini="${ini//[/\[}"          # escape [
    ini="${ini//]/\]}"          # escape ]
    IFS=$'\n' && ini=( ${ini} ) # convert to line-array
    ini=( ${ini[*]//;*/} )      # remove comments with ;
    ini=( ${ini[*]/\    =/=} )  # remove tabs before =
    ini=( ${ini[*]/=\   /=} )   # remove tabs be =
    ini=( ${ini[*]/\ =\ /=} )   # remove anything with a space around =
    ini=( ${ini[*]/#\\[/\}$'\n'cfg.section.} ) # set …
Run Code Online (Sandbox Code Playgroud)

bash shell-script regular-expression

5
推荐指数
1
解决办法
9351
查看次数

为什么这个循环中的printf语句会乱序输出数组?

当我执行以下代码时,printf 语句的输出似乎显示数组乱序。在声明语句中,源项在目标之前声明,而在输出中则相反。

YELLOW=$'\e[93m'
declare -A OP=( [Description]="remote to destination" [Source]="/var/www" [Destination]="/foo/bar" [Log]="my.log" [Email]="me@here" );

NO_COLS=`tput cols`
COLS_PER_COL=$(($NO_COLS/3))
PRINT_FORMAT="%"$COLS_PER_COL"s%""s\n"

for i in "${!OP[@]}"; do
    printf $PRINT_FORMAT "$i :" " $YELLOW${OP[$i]}$ENDCOL"
done ;
Run Code Online (Sandbox Code Playgroud)

输出看起来像

         Description : remote to destination
         Destination : /foo/bar
              Source : /var/www
                 Log : my.log
               Email : me@here
Run Code Online (Sandbox Code Playgroud)

谁能告诉我这里发生了什么?或者如何根据数组声明实现正确的顺序?

bash array shell-script

2
推荐指数
1
解决办法
596
查看次数

标签 统计

bash ×4

shell-script ×4

array ×2

regular-expression ×1