繁体   English   中英

我如何使命令成为变量

[英]How do I make a command a variable

这里是一个相对新手。 我正在使用以下命令读取文件:

while read line
 do 
      commands here
done < file

我将线分为两部分,以下用破折号分隔

dash_pos=`expr index "$line" -`

dash_pos显然不是常量,这就是为什么我将其dash_pos变量。

我现在可以执行以下操作

Part1=${line:0:$dash_pos -2}
Part2=${line:$dash_pos + 1}

这些命令按预期方式工作。

有没有一种方法可以使字符串操作命令成为变量,例如

Find_Part1=${line:0:$dash_pos -2}
Find_Part2=${line:$dash_pos + 1}

以便

  Part1=$Find_Part1  &   Part2=$Find_Part2

像以前一样工作,但是它将允许我做

 Part1=$Find_Part2   &   Part2=$Find_Part1

必要时。

任何帮助将不胜感激,因为我尝试了各种组合的引号,双引号,方括号,大括号和反勾号,以尝试使此方法起作用。 约翰

将可执行代码存储在变量中的麻烦远不止于此。 使用函数代替:

Find_Part1 () {
    printf "%s" "${line:0:$dash_pos -2}"
}

Find_Part2 () {
    printf "%s" "${line:$dash_pos + 1}"
}

Part1=$(Find_Part1)
Part2=$(Find_Part2)

但是,您似乎真正想要的是

while IFS="-" read Part1 Part2; do
   ...
done < file

read命令为您将line分为Part1Part2

目前尚不清楚为什么您不能仅仅执行问题中的字面意思:

# get the parts
Find_Part1=${line:0:$dash_pos -2}
Find_Part2=${line:$dash_pos + 1}

# ... as necessary:

if such and such condition ; then
   Part1=$Find_Part1
   Part2-$Find_Part2
else
   Part1=$Find_Part2
   Part2=$Find_Part1
fi

另外,您可以根据需要交换Part1Part2的值,只需要一个临时变量

if interesting condition ; then
    temp=$Part1; Part1=$Part2; Part2=$temp
fi

在Bash函数内部,我们可能将temp为local,以避免名称冲突和名称空间混乱:

local temp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM