Bash 如何使命令成为变量

Bash 如何使命令成为变量,bash,shell,Bash,Shell,一个相对的新手。 我正在使用以下命令读取文件: while read line do commands here done < file dash_pos显然不是一个常数,这就是为什么我把它设为变量 我现在可以做以下事情了 dash_pos=`expr index "$line" -` Part1=${line:0:$dash_pos -2} Part2=${line:$dash_pos + 1} 这些命令按预期工作 有没有一种方法可以使字符串操作命令成为变量,例如

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

while read line
 do 
      commands here
done < file
dash_pos
显然不是一个常数,这就是为什么我把它设为变量

我现在可以做以下事情了

dash_pos=`expr index "$line" -`
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
必要时

任何帮助都将不胜感激,因为我尝试了引号、双引号、括号、, 花括号和背勾有多种组合,以尝试获得此效果 工作。
John

将可执行代码存储在变量中的麻烦远远超过了它的价值。改用函数:

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
而IFS=“-”读取第1部分第2部分;做
...
完成<文件

read
命令将
拆分为
第1部分
第2部分

不清楚您为什么不能按问题的字面意思执行:

# 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
此外,您还可以在必要时交换
Part1
Part2
的值,只需要一个临时变量

if interesting condition ; then
    temp=$Part1; Part1=$Part2; Part2=$temp
fi
在Bash函数中,我们可以将
temp
设置为本地,以避免名称冲突和名称空间混乱:

local temp

我不知道你想达到什么目的。您可以添加一些您期望的示例输入/输出和功能吗?我真的不明白切换变量名的意义。您确定这不是XY问题吗:您可以使用
eval
,它应该读作“邪恶”,因为它是。通常有比使用邪恶更好的方法,但我不知道你为什么要这么做。也许考虑使用一个函数?(“我想在一个变量中设置一个命令,但是复杂的情况总是失败!”)代码> PART1=$FunthPART1&PART2= $FunthPART2。你为什么要把作业命令放在后台?嗨,伯恩哈德,我正在用曲目列表文本文件标记大量的mp3文件,其中一些有Title-Artist,而另一些有Artist-Title。我将这两个部分放入数组中,但在输出到文件时需要保持它们的有序。感谢您的建议,但我试图避免在每一行输入中使用IF。文本文件将要么是标题-艺术家或艺术家-标题完全,所以问题只需要回答一次。约翰:你怎么知道哪一行是以标题开头的,哪一行是以艺术家开头的?嗨,卡兹,如上所述,但我会保留你的想法。约翰