相关疑难解决方法(0)

如何将输入传递给Bash while循环并在循环结束后保留​​变量

Bash允许使用: cat <(echo "$FILECONTENT")

Bash还允许使用: while read i; do echo $i; done </etc/passwd

结合前两个可以使用: echo $FILECONTENT | while read i; do echo $i; done

最后一个问题是它创建了子shell,而在while循环结束后,变量i不再被访问.

我的问题是:

如何实现这样的目标:while read i; do echo $i; done <(echo "$FILECONTENT")或者换句话说:我怎样才能确定i循环中存活?

请注意我知道封闭while语句{}但这并不能解决问题(想象一下你想在函数中使用while循环并返回i变量)

bash stdin pipe while-loop

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

如何在 bash 中从文本文件创建字典?

我想从一个文本文件在 bash 中创建一个字典,如下所示:

H96400275|A
H96400276|B
H96400265|C
H96400286|D
Run Code Online (Sandbox Code Playgroud)

基本上我想要一个来自这个文件的字典file.txt

KEYS        VALUES
H96400275 = A
H96400276 = B
H96400265 = C
H96400286 = D
Run Code Online (Sandbox Code Playgroud)

我创建了以下脚本:

#!/bin/bash
declare -a dictionary

while read line; do 

  key=$(echo $line | cut -d "|" -f1)
  data=$(echo $line | cut -d "|" -f2)
  dictionary[$key]="$data"
done < file.txt


echo ${dictionary[H96400275]}
Run Code Online (Sandbox Code Playgroud)

但是,这不会打印A,而是打印D。你能帮忙吗?

bash shell dictionary

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

标签 统计

bash ×2

dictionary ×1

pipe ×1

shell ×1

stdin ×1

while-loop ×1