Mat*_*NNZ 6 string bash string-concatenation sh
我有一个源变量,基本上是一串逗号分隔的元素:
SOURCES="a b c d e"
Run Code Online (Sandbox Code Playgroud)
我希望用户为每个源输入一个目的地,因此我希望将此输入存储到类似于上面但包含目的地的字符串中.如果我想分配a = 1,b = 2 ......等,我会这样:
echo $DESTINATIONS >>> "1 2 3 4 5"
Run Code Online (Sandbox Code Playgroud)
为了做到这一点,我这样做:
SOURCES="a b c d e"
DESTINATIONS=""
for src in $SOURCES
do
echo Input destination to associate to the source $src:
read dest
DESTINATIONS=$DESTINATIONS $dest
done
Run Code Online (Sandbox Code Playgroud)
但是,如果我做一个echo上$DESTINATIONS,我觉得很空.而且,在每个循环中,我的shell告诉我:
-bash: = **myInput**: command not found
Run Code Online (Sandbox Code Playgroud)
知道我哪里做错了吗?
您应该使用数组,而不是分隔字符串。
sources=(a b c d e)
for src in "${sources[@]}"
do
read -p "Input destination to associate to the source $src" dest
destinations+=( "$dest" )
done
printf '%s\n' "${destinations[@]}"
Run Code Online (Sandbox Code Playgroud)
小智 5
SOURCES="a b c d e"
DESTINATIONS=""
for src in $SOURCES
do
echo Input destination to associate to the source $src:
read dest
DESTINATIONS+=" ${dest}"
done
echo $DESTINATIONS
Run Code Online (Sandbox Code Playgroud)
适合我.