将Bash命令的结果存储在Shell变量中[duplicate]

cgh8pdjw  于 2022-11-16  发布在  Shell
关注(0)|答案(1)|浏览(154)

此问题在此处已有答案

How do I set a variable to the output of a command in Bash?(15个答案)
28天前关闭。
我尝试将bash命令的结果存储在for循环中,以便在命令中使用。

for filename in /home/WIN/USER/files/*
var=$(basename ${filename%.*}) | awk -F'[_.]' '{print $1}'
do echo var
done

但是,我收到以下错误:

./script.sh: line 2: syntax error near unexpected token `var=$(basename ${filename%.*})'
./script.sh: line 2: `var=$(basename ${filename%.*}) | awk -F'[_.]' '{print $1}''

有没有人知道如何解决这个问题或者如何做我正在努力做的事情?

  • 谢谢-谢谢
8oomwypt

8oomwypt1#

你的for语句是错误的,你的变量赋值语句也是错误的,你应该这样写:

for filename in /home/WIN/USER/files/*; do
    var=$( your shell code goes here ) # you assign the output of the shell code here
    echo "$var" # you echo the results here
done

相关问题